package cc.rengu.igas.momp.core.service.trans;

import cc.rengu.igas.momp.common.constant.CommonConstant;
import cc.rengu.igas.momp.common.dao.*;
import cc.rengu.igas.momp.common.dao.impl.*;
import cc.rengu.igas.momp.common.entity.*;
import cc.rengu.igas.momp.common.enums.*;
import cc.rengu.igas.momp.common.model.bean.JsonTmpMfdMcInfo;
import cc.rengu.igas.momp.common.util.CommonMessageCheck;
import cc.rengu.igas.momp.common.util.JsonOperation;
import cc.rengu.igas.momp.common.util.McInfoDbOperation;
import cc.rengu.igas.momp.common.util.MompDateUtil;
import cc.rengu.igas.momp.facade.request.PublishMchntFeeDiscountMcRequest;
import cc.rengu.igas.momp.facade.response.PublishMchntFeeDiscountMcResponse;
import cc.rengu.jradp.mods.dbs.Database;
import cc.rengu.oltp.service.base.RadpService;
import cc.rengu.oltp.service.common.constant.AppConfigConstant;
import cc.rengu.oltp.service.common.constant.AppParamConstant;
import cc.rengu.oltp.service.common.constant.TreeNodeConstant;
import cc.rengu.oltp.service.common.enums.ChannelEnum;
import cc.rengu.oltp.service.common.enums.OltpRpcdEnum;
import cc.rengu.oltp.service.model.BizException;
import cc.rengu.oltp.service.model.BizResponse;
import cc.rengu.oltp.utility.bean.PageInfo;
import cc.rengu.oltp.utility.bean.PageResult;
import cc.rengu.oltp.utility.util.*;
import cc.rengu.utility.base.StringUtil;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 商户手续费优惠类营销活动发布
 *
 * @author Jinan Liu
 * @version 1.0.0
 * @date 2020/4/2 17:45
 */

public class PublishMchntFeeDiscountMcService extends RadpService {

    private String globalInstId;
    private String globalMcNo;
    private String globalTimeStamp;
    private String globalOprId;
    private String queryType;
    private String queryRole;
    private String oprType;
    private TMMcMchntFeeDiscountInfo tmMcMchntFeeDiscountInfo;
    private String mcStatus;
    private String globalTxnDate;
    private String beforeFlag;
    private String adterFlag;
    private String stockMchntFlag;
    private String relationMcNo;
    private String mcStartDate;
    private String mcEndDate;
    private String monthCount;
    private String stockMchntType;
    private String flow;
    private static final String TABLE_NAME = TableNameEnum.T_M_MC_MFD_INFO.getTableNameCode();
    /**
     * 手续费达标统计表数据
     */
    private List<TMStatMfdCriteria> allSmStatMfdCriteriaList = new ArrayList<>();
    /**
     * 营销活动商户统计表数据
     */
    private List<TMStatMfdMchnt> tmStatMfdMchntList = new ArrayList<>();
    /**
     * 审批状态
     */
    private String auditStatus;
    /**
     * 拒绝原因
     */
    private String oprContent;
    /**
     * 状态
     */
    private String bizStatus;

    @Override
    protected int bizInit(String s) {
        return CommonConstant.PROCESS_SUCCESS;
    }

    @Override
    protected int bizProcess(String s, int i) {

        XmlTreeUtil xmlTreeUtil = new XmlTreeUtil();

        try {

            PublishMchntFeeDiscountMcRequest publishMchntFeeDiscountMcRequest = new PublishMchntFeeDiscountMcRequest();
            ConvertUtil.convertOutput(publishMchntFeeDiscountMcRequest);

            PublishMchntFeeDiscountMcResponse publishMchntFeeDiscountMcResponse = new PublishMchntFeeDiscountMcResponse();
            publishMchntFeeDiscountMcResponse.setHeader(publishMchntFeeDiscountMcRequest.getHeader());
            BizResponse<PublishMchntFeeDiscountMcResponse> bizResponse = new BizResponse<>();
            bizResponse.setResult(publishMchntFeeDiscountMcResponse);

            globalInstId = publishMchntFeeDiscountMcRequest.getHeader().getInstId();
            globalMcNo = publishMchntFeeDiscountMcRequest.getMcNo();
            globalTimeStamp = new SimpleDateFormat(CommonConstant.TIMESTAMP_FORMAT).format(new Date());
            globalOprId = publishMchntFeeDiscountMcRequest.getQueryId();

            rglog.info("机构<{}>的营销活动<{}>在<{}>由<{}>开始发布流程", globalInstId, globalMcNo, globalTimeStamp, globalOprId);

            queryType = publishMchntFeeDiscountMcRequest.getQueryType();
            queryRole = publishMchntFeeDiscountMcRequest.getQueryRole();
            oprType = publishMchntFeeDiscountMcRequest.getOprType();
            globalTxnDate = publishMchntFeeDiscountMcRequest.getHeader().getTransDate();
            oprContent = publishMchntFeeDiscountMcRequest.getOprContent();

            /* 报文检查 */
            CommonMessageCheck.checkBizMessageHeader(queryType, globalOprId, queryRole, rglog);
            CommonMessageCheck.checkSingleValue(oprType, rglog);
//            if (oprType.equals(CommonConstant.ZERO_COMMON_CONSTANT)){
//                //判断未上送商户号商圈号时，机构下的非特殊费率商户达标统计表是否存该交易日期内的数据
//                checkMchntNoAndAreaNo(xmlTreeUtil,publishMchntFeeDiscountMcRequest);
//            }
            // 服务调用
            BizResponse<PublishMchntFeeDiscountMcResponse> bizResponseNew = publishMchntFeeDiscountMc(publishMchntFeeDiscountMcRequest, publishMchntFeeDiscountMcResponse, xmlTreeUtil);

            ConvertUtil.convertInput(bizResponseNew.getResult());

        } catch (BizException e) {
            try {
                xmlTreeUtil.setXmlTreeStringValue(TreeNodeConstant.RESP_CODE, e.getCode());
                xmlTreeUtil.setXmlTreeStringValue(TreeNodeConstant.RESP_DESC, e.getMessage());
                xmlTreeUtil.setXmlTreeStringValue(CommonConstant.KEY_RESPDESC, e.getMessage());
            } catch (Exception e1) {
                rglog.error(StringUtil.ExceptionToString(e1));
            }
        } catch (Exception e) {
            rglog.error(StringUtil.ExceptionToString(e));
            try {
                xmlTreeUtil.setXmlTreeStringValue(TreeNodeConstant.RESP_CODE, OltpRpcdEnum.OLTP_PROCESS_ERROR.getRespCode());
                xmlTreeUtil.setXmlTreeStringValue(TreeNodeConstant.RESP_DESC, OltpRpcdEnum.OLTP_PROCESS_ERROR.getRespDesc());
                xmlTreeUtil.setXmlTreeStringValue(CommonConstant.KEY_RESPDESC, e.getMessage());
            } catch (Exception e1) {
                rglog.error(StringUtil.ExceptionToString(e));
            }
        }

        return CommonConstant.PROCESS_SUCCESS;
    }

    @Override
    protected int bizTerminate(String s) {
        return CommonConstant.PROCESS_SUCCESS;
    }


    /**
     * 发布商户手续费优惠类营销活动
     *
     * @param publishMchntFeeDiscountMcRequest  商户手续费优惠类活动发布接口请求对象
     * @param publishMchntFeeDiscountMcResponse 商户手续费优惠类活动发布接口应答对象
     * @param xmlTreeUtil                       内部XML树
     * @return cc.rengu.oltp.service.model.BizResponse<cc.rengu.igas.momp.facade.response.PublishMchntFeeDiscountMcResponse> 商户手续费优惠类活动发布接口应答对象
     * @throws BizException 异常信息
     * @author Jinan Liu
     * @date 2020/5/23 16:59
     */
    private BizResponse<PublishMchntFeeDiscountMcResponse> publishMchntFeeDiscountMc(PublishMchntFeeDiscountMcRequest publishMchntFeeDiscountMcRequest, PublishMchntFeeDiscountMcResponse publishMchntFeeDiscountMcResponse, XmlTreeUtil xmlTreeUtil)
            throws Exception {

        BizResponse<PublishMchntFeeDiscountMcResponse> bizResponse = new BizResponse<>();

        /* 判断用户的角色和权限 */
        if (QueryRoleEnum.BANK_PUBLISH_QYERY_ROLE.getQueryRoleCode().equals(queryRole)) {
            /* 银行录入岗操作 */
            if (QueryTypeEnum.BANK_QUERY_TYPE.getQueryTypeCode().equals(queryType)) {

                /* 取营销活动正式表和临时表的各种状态 */
                checkMcStatus(publishMchntFeeDiscountMcRequest.getOprType());

                /* 判断操作类型 */
                if (OprTypeEnum.PUBLISH_PASSED.getOprTypeCode().equals(oprType)) {
                    /* 发布通过 */
                    publishMc(xmlTreeUtil, publishMchntFeeDiscountMcRequest);
                } else if (OprTypeEnum.PUBLISH_REFUSED.getOprTypeCode().equals(oprType)) {
                    /* 发布拒绝 */
                    refusePublishMc(xmlTreeUtil, publishMchntFeeDiscountMcRequest);
                } else if (OprTypeEnum.FORCE_DISABLE.getOprTypeCode().equals(oprType)) {
                    /* 强制终止活动 */
                    forceStopMc(xmlTreeUtil);
                } else if (OprTypeEnum.ENABLE.getOprTypeCode().equals(oprType)) {
                    /* 启用活动 */
                    enableMc(xmlTreeUtil);
                } else if (OprTypeEnum.PAUSE.getOprTypeCode().equals(oprType)) {
                    /* 暂停活动 */
                    pauseMc(xmlTreeUtil);
                } else {
                    /* 不支持的操作类型 */
                    rglog.error("<{}>, OPR_TYPE=<{}>", RespCodeEnum.NOT_SUPPORTED_OPR_TYPE_ERROR.getRespDesc(), oprType);
                    throw new BizException(RespCodeEnum.NOT_SUPPORTED_OPR_TYPE_ERROR.getRespCode(), RespCodeEnum.NOT_SUPPORTED_OPR_TYPE_ERROR.getRespDesc());
                }

            } else {
                /* 非银行人员无权限操作数据 */
                rglog.error("当前<{}>角色的查询用户<{}>无权限操作数据!", queryRole, queryType);
                throw new BizException(RespCodeEnum.NO_AUTHORIZATION_TO_OPER_ERROR.getRespCode(), RespCodeEnum.NO_AUTHORIZATION_TO_OPER_ERROR.getRespDesc());
            }

        } else {
            /* 非银行录入岗无权限操作数据 */
            rglog.error("当前<{}>角色的查询用户<{}>无权限操作数据!", queryRole, queryType);
            throw new BizException(RespCodeEnum.NO_AUTHORIZATION_TO_OPER_ERROR.getRespCode(), RespCodeEnum.NO_AUTHORIZATION_TO_OPER_ERROR.getRespDesc());
        }

        bizResponse.setRspSysId(ChannelEnum.MOMP.getChannelType());
        bizResponse.setRespCode(RespCodeEnum.TRANS_SUCCESS.getRespCode());
        bizResponse.setRespDesc(RespCodeEnum.TRANS_SUCCESS.getRespDesc());

        publishMchntFeeDiscountMcResponse.setRespCode(RespCodeEnum.TRANS_SUCCESS.getRespCode());
        publishMchntFeeDiscountMcResponse.setRespDesc(RespCodeEnum.TRANS_SUCCESS.getRespDesc());
        bizResponse.setResult(publishMchntFeeDiscountMcResponse);

        return bizResponse;
    }

    /**
     * 判断营销活动状态是否可以发布通过或者发布拒绝
     * 未抛异常说明营销活动状态正常
     * 全局变量mcStatus作为判断当前营销活动是否发布的标志
     *
     * @param oprType 操作类型
     * @throws Exception 异常信息
     * @author Jinan Liu
     * @date 2020/5/25 22:10
     */
    private void checkMcStatus(String oprType) throws Exception {

        /* 查询正式表数据 */
        TMMcMchntFeeDiscountInfo tmMcMchntFeeDiscountInfo = (TMMcMchntFeeDiscountInfo) McInfoDbOperation.getMcInfo(rglog, globalInstId, globalMcNo, TABLE_NAME);
        if (null == tmMcMchntFeeDiscountInfo) {
            rglog.error("未获取到机构<{}>的营销活动编号<{}>的营销活动基本信息", globalInstId, globalMcNo);
            throw new BizException(RespCodeEnum.GET_MCHNT_FEE_DISCOUNT_MC_DETAIL_ERROR.getRespCode(), RespCodeEnum.GET_MCHNT_FEE_DISCOUNT_MC_DETAIL_ERROR.getRespDesc());
        }
        mcEndDate = tmMcMchntFeeDiscountInfo.getMcEndDate();
        this.tmMcMchntFeeDiscountInfo = tmMcMchntFeeDiscountInfo;
        //判断是不是转移商户
        flow = "1";
        /* 查询临时表数据 */
        TMPlatBizTmp tmPlatBizTmp = McInfoDbOperation.getTmpMcInfo(rglog, globalInstId, globalMcNo, TABLE_NAME);
        if (null == tmPlatBizTmp) {
            rglog.error("未获取到机构<{}>的营销活动编号<{}>的营销活动基本信息", globalInstId, globalMcNo);
            throw new BizException(RespCodeEnum.GET_MCHNT_FEE_DISCOUNT_MC_DETAIL_ERROR.getRespCode(), RespCodeEnum.GET_MCHNT_FEE_DISCOUNT_MC_DETAIL_ERROR.getRespDesc());
        }

        if (OprTypeEnum.PUBLISH_PASSED.getOprTypeCode().equals(oprType) ||
                OprTypeEnum.PUBLISH_REFUSED.getOprTypeCode().equals(oprType)) {
            /* 发布营销活动检查项，和拒绝发布流程相同，共用一套判断流程 */
            /* 拒绝发布营销活动检查项，和发布通过流程相同，共用一套判断流程 */
            /* 临时表中营销活动状态不是未发布的不可发布通过 */
            if (!McStatusEnum.NOT_PUBLISHED.getMcStatusCode().equals(tmPlatBizTmp.getMcStatus()) && !McStatusEnum.PROGRESSING.getMcStatusCode().equals(tmPlatBizTmp.getMcStatus())) {
                rglog.error("机构<{}>的营销活动编号<{}>临时表中的营销活动状态<{}>异常，不可发布通过或发布拒绝", globalInstId, globalMcNo, tmPlatBizTmp.getMcStatus());
                throw new BizException(RespCodeEnum.WRONG_TMP_MC_STATUS_TO_PASS_PUBLISH_ERROR.getRespCode(), RespCodeEnum.WRONG_TMP_MC_STATUS_TO_PASS_PUBLISH_ERROR.getRespDesc());
            }

            /* 临时表中营销活动审批状态不是发布审批中的不可发布通过 */
            if (!AuditStatusEnum.PUBLISH_AUDIT_PROCESSING.getAuditStatusCode().equals(tmPlatBizTmp.getAuditStatus())) {
                rglog.error("机构<{}>的营销活动编号<{}>临时表中的营销活动审批状态<{}>异常，不可发布通过或发布拒绝", globalInstId, globalMcNo, tmPlatBizTmp.getAuditStatus());
                throw new BizException(RespCodeEnum.WRONG_TMP_AUDIT_STATUS_TO_REFUSE_PUBLISH_ERROR.getRespCode(), RespCodeEnum.WRONG_TMP_AUDIT_STATUS_TO_REFUSE_PUBLISH_ERROR.getRespDesc());
            }

            /* 判断营销活动是否在进行中 */
            if (McStatusEnum.PROGRESSING.getMcStatusCode().equals(this.tmMcMchntFeeDiscountInfo.getMcStatus())) {
                /* 营销活动在进行中 */
                this.mcStatus = McStatusEnum.PROGRESSING.getMcStatusCode();
            } else {
                /* 营销活动不是进行中的状态 */
                if (!McStatusEnum.NOT_PUBLISHED.getMcStatusCode().equals(this.tmMcMchntFeeDiscountInfo.getMcStatus())) {
                    rglog.error("机构<{}>的营销活动编号<{}>的营销活动状态<{}>异常，不可发布通过或发布拒绝", globalInstId, globalMcNo, this.tmMcMchntFeeDiscountInfo.getMcStatus());
                    throw new BizException(RespCodeEnum.WRONG_MC_STATUS_TO_PASS_PUBLISH_ERROR.getRespCode(), RespCodeEnum.WRONG_MC_STATUS_TO_PASS_PUBLISH_ERROR.getRespDesc());
                }

                if (!AuditStatusEnum.PUBLISH_AUDIT_PROCESSING.getAuditStatusCode().equals(this.tmMcMchntFeeDiscountInfo.getAuditStatus())) {
                    rglog.error("机构<{}>的营销活动编号<{}>的营销活动审批状态<{}>异常，不可发布通过或发布拒绝", globalInstId, globalMcNo, this.tmMcMchntFeeDiscountInfo.getAuditStatus());
                    throw new BizException(RespCodeEnum.WRONG_AUDIT_STATUS_TO_REFUSE_PUBLISH_ERROR.getRespCode(), RespCodeEnum.WRONG_AUDIT_STATUS_TO_REFUSE_PUBLISH_ERROR.getRespDesc());
                }

                this.mcStatus = McStatusEnum.NOT_PUBLISHED.getMcStatusCode();
            }
        } else if (oprType.equals(OprTypeEnum.FORCE_DISABLE.getOprTypeCode())) {//活动强制终止
            if ((!this.tmMcMchntFeeDiscountInfo.getMcStatus().equals(McStatusEnum.PROGRESSING.getMcStatusCode()) && !this.tmMcMchntFeeDiscountInfo.getMcStatus().equals(McStatusEnum.PAUSED.getMcStatusCode()))) {
                rglog.error("机构<{}>的营销活动编号<{}>的营销活动状态<{}>不是进行中或已暂停，不可强制终止", globalInstId, globalMcNo, this.tmMcMchntFeeDiscountInfo.getMcStatus());
                throw new BizException(RespCodeEnum.WRONG_MC_STATUS_TO_FORCE_DISABLE_ERROR.getRespCode(), RespCodeEnum.WRONG_MC_STATUS_TO_FORCE_DISABLE_ERROR.getRespDesc());
            }
        } else if (oprType.equals(OprTypeEnum.PAUSE.getOprTypeCode())) {//活动暂停
            if (!this.tmMcMchntFeeDiscountInfo.getMcStatus().equals(McStatusEnum.PROGRESSING.getMcStatusCode())) {
                rglog.error("机构<{}>的营销活动编号<{}>的营销活动状态<{}>不是进行中，不可暂停", globalInstId, globalMcNo, this.tmMcMchntFeeDiscountInfo.getMcStatus());
                throw new BizException(RespCodeEnum.WRONG_MC_STATUS_TO_PAUSE_ERROR.getRespCode(), RespCodeEnum.WRONG_MC_STATUS_TO_PAUSE_ERROR.getRespDesc());
            }
        } else if (oprType.equals(OprTypeEnum.ENABLE.getOprTypeCode())) {//活动启用
            if (!this.tmMcMchntFeeDiscountInfo.getMcStatus().equals(McStatusEnum.PAUSED.getMcStatusCode())) {
                rglog.error("机构<{}>的营销活动编号<{}>的营销活动状态<{}>不是已暂停，不可启用活动", globalInstId, globalMcNo, this.tmMcMchntFeeDiscountInfo.getMcStatus());
                throw new BizException(RespCodeEnum.WRONG_MC_STATUS_TO_ENABLE_ERROR.getRespCode(), RespCodeEnum.WRONG_MC_STATUS_TO_ENABLE_ERROR.getRespDesc());
            }
        } else {
            /* 不支持的操作类型 */
            rglog.error("<{}>, OPR_TYPE=<{}>", RespCodeEnum.NOT_SUPPORTED_OPR_TYPE_ERROR.getRespDesc(), oprType);
            throw new BizException(RespCodeEnum.NOT_SUPPORTED_OPR_TYPE_ERROR.getRespCode(), RespCodeEnum.NOT_SUPPORTED_OPR_TYPE_ERROR.getRespDesc());
        }

    }

    /**
     * 营销活动发布通过流程
     *
     * @param xmlTreeUtil                      内部XML树
     * @param publishMchntFeeDiscountMcRequest 商户手续费优惠类活动发布接口请求对象
     * @throws Exception 异常信息
     * @author Jinan Liu
     * @date 2020/5/25 22:50
     */
    private void publishMc(XmlTreeUtil xmlTreeUtil, PublishMchntFeeDiscountMcRequest publishMchntFeeDiscountMcRequest) throws Exception {
        /* 开启数据库事务 */
        String dbPoolName = XmlConfigUtil.getXmlConfigCacheKeyValue(AppConfigConstant.DATABASE_CONF_NODE, AppConfigConstant.MOMP_POOL_NAME);
        String corporation = xmlTreeUtil.getXmlTreeStringValue(AppParamConstant.CORPORATION);
        if (null != corporation && !corporation.isEmpty()) {
            String dbPoolCashNode = corporation.trim() + AppParamConstant.DATABASE_CONF_NODE;
            dbPoolName = XmlConfigUtil.getXmlConfigCacheKeyValue(dbPoolCashNode, AppConfigConstant.MOMP_POOL_NAME);
        }
        DbsUtil dbsUtil = new DbsUtil(dbPoolName);
        dbsUtil.dbsBeginTransaction();
        McMchntInfoMapper mcMchntInfoMapper = new McMchntInfoMapperImpl();
        /* 根据营销活动状态走入对应的业务流程 */
        int returnCode;
        if (McStatusEnum.PROGRESSING.getMcStatusCode().equals(this.mcStatus)) {
            //取营销活动信息表
            McDetailInfoMapper mcDetailInfoMapper = new McDetailInfoMapperImpl();
            MfdMcListInfoInObj mfdMcListInfoInObj = new MfdMcListInfoInObj();
            mfdMcListInfoInObj.setInstId(globalInstId);
            mfdMcListInfoInObj.setMcNo(globalMcNo);
            mfdMcListInfoInObj.setOrgId(publishMchntFeeDiscountMcRequest.getQueryOrgId());
            TMMcMchntFeeDiscountInfo tmMcMchntFeeDiscountInfo = mcDetailInfoMapper.selectMfdMcDetailInfoByBankBasicRole(mfdMcListInfoInObj);
            adterFlag = tmMcMchntFeeDiscountInfo.getAfterFlag();
            beforeFlag = tmMcMchntFeeDiscountInfo.getBeforeFlag();
            stockMchntFlag = tmMcMchntFeeDiscountInfo.getStockMchntFlag();
            mcStartDate = tmMcMchntFeeDiscountInfo.getMcStartDate();
            mcEndDate = tmMcMchntFeeDiscountInfo.getMcEndDate();
            monthCount = tmMcMchntFeeDiscountInfo.getDepositMonNum();
            stockMchntType = tmMcMchntFeeDiscountInfo.getStockMchntType();
            /* 取新增商户数据 */
            TMPlatBizTmp tmPlatBizTmp = new TMPlatBizTmp();
            tmPlatBizTmp.setInstId(globalInstId);
            tmPlatBizTmp.setMcNo(globalMcNo);
            tmPlatBizTmp.setOprTableEname(TableNameEnum.T_M_MC_MCHNT_INFO.getTableNameCode());
            tmPlatBizTmp.setBizStatus(BizStatusEnum.NORMAL_STATUS.getBizStatusCode());
            tmPlatBizTmp.setMcStatus(McStatusEnum.NOT_PUBLISHED.getMcStatusCode());
            tmPlatBizTmp.setAuditStatus(AuditStatusEnum.PUBLISH_AUDIT_PROCESSING.getAuditStatusCode());
            List<TMPlatBizTmp> tmPlatBizTmpList = selectNewAddedMchntInfoForPublishing(tmPlatBizTmp);
            //如果新增商户数据为空，说明进行中新增商户被拒后删除，直接修改活动状态
            if (null == tmPlatBizTmpList || tmPlatBizTmpList.isEmpty()) {
                TMMcMchntFeeDiscountInfo tmMcMchntFeeDiscountInfo1 = new TMMcMchntFeeDiscountInfo();
                tmMcMchntFeeDiscountInfo1.setInstId(globalInstId);
                tmMcMchntFeeDiscountInfo1.setMcNo(globalMcNo);
                tmMcMchntFeeDiscountInfo1.setMcStatus(McStatusEnum.PROGRESSING.getMcStatusCode());
                tmMcMchntFeeDiscountInfo1.setRemark1(AuditStatusEnum.PUBLISH_AUDIT_PROCESSING.getAuditStatusCode());
                tmMcMchntFeeDiscountInfo1.setAuditStatus(AuditStatusEnum.PUBLISH_AUDIT_PASSED.getAuditStatusCode());
                /* 更新营销活动预算数据 */
                returnCode = mcDetailInfoMapper.updataMcStatusForPublish(tmMcMchntFeeDiscountInfo1);
                if (Database.DBS_SUCCESS != returnCode) {
                    rglog.error("更新机构<{}>商户手续费优惠类营销活动<{}>营销活动状态失败!", globalInstId, globalMcNo);
                    dbsUtil.dbsEndTransaction(false);
                    throw new BizException(RespCodeEnum.SYSTEM_ERROR.getRespCode(), RespCodeEnum.SYSTEM_ERROR.getRespDesc());
                }
            } else {
                //进行中新增商户列表
                List<TMMcMchntInfo> tmMcMchntInfoList = getAllMcMchntListInfoByinstIdMcMoFlag(CommonConstant.MC_EXIT_FLAG, CommonConstant.MCHNT_NEW_FLAG);
                MchntInfoMapper mchntInfoMapper = new MchntInfoMapperImpl();
                PlatBizTmpMapper platBizTmpMapper = new PlatBizTmpMapperImpl();
                //进行中新增商户列表不为空走该流程
                if (null != tmMcMchntInfoList && tmMcMchntInfoList.size() > 0) {
                    for (TMMcMchntInfo tmMcMchntInfo : tmMcMchntInfoList) {
                        //判断商户是否存在特殊费率
                        List<TBMchntFeeInfo> tbMchntFeeInfoList = mchntInfoMapper.selectMchntFeeInfoListByMchntNo(globalInstId, tmMcMchntInfo.getMchntNo());
                        if (null != tbMchntFeeInfoList && tbMchntFeeInfoList.size() > 0) {
                            tbMchntFeeInfoList = tbMchntFeeInfoList.stream().filter(item -> item.getFeeInputMode().equals(CommonConstant.ZERO_COMMON_CONSTANT)).collect(Collectors.toList());
                            if (null != tbMchntFeeInfoList && tbMchntFeeInfoList.size() > 0) {
                                rglog.error("商户<{}>费率信息表存在特殊费率！", tmMcMchntInfo.getMchntNo());
                                throw new BizException(RespCodeEnum.EXISTENCE_SPECIAL_FEE.getRespCode(), RespCodeEnum.EXISTENCE_SPECIAL_FEE.getRespDesc());
                            }
                        }
                        //查询手续费达标统计表是否有该商户现交易日期达标的数据
                        TMStatMfdCriteriaMapper tmStatMfdCriteriaMapper = new TMStatMfdCriteriaMapperImpl();
                        TMStatMfdCriteria tmStatMfdCriteria = tmStatMfdCriteriaMapper.selectTMStatMfdCriteriaByUsingMchntNoAndDateRange(globalInstId, tmMcMchntInfo.getMchntNo(), globalTxnDate);
                        //如果达标统计表有当前交易日期商户达标的数据，则直接拒绝新增,原活动状态为自然结束，强制结束，已结束的数据作废
                        if (null != tmStatMfdCriteria) {
                            /* 营销活动信息正式表查询 */
                            TMMcMchntFeeDiscountInfo tmMcMchntFeeDiscountInfo1 = (TMMcMchntFeeDiscountInfo) mcDetailInfoMapper.selectMcDetailInfo(globalInstId, tmStatMfdCriteria.getMcNo(), TABLE_NAME);
                            if (null != tmStatMfdCriteria && (null == tmMcMchntFeeDiscountInfo1 || tmMcMchntFeeDiscountInfo1.getMcStatus().equals(McStatusEnum.ENDED.getMcStatusCode()) || tmMcMchntFeeDiscountInfo1.getMcStatus().equals(McStatusEnum.FORCE_ENDED.getMcStatusCode()) || tmMcMchntFeeDiscountInfo1.getMcStatus().equals(McStatusEnum.ALL_ENDED.getMcStatusCode()))) {
                                rglog.error("交易流水号：<{}>, 商户<{}>已参加其他手续费活动！", publishMchntFeeDiscountMcRequest.getHeader().getTraceNo(), tmMcMchntInfo.getMchntNo());
                                throw new BizException(RespCodeEnum.WRONG_MCHNT_ISALREADY_ORTHER_INMC_ERROR.getRespCode(), RespCodeEnum.WRONG_MCHNT_ISALREADY_ORTHER_INMC_ERROR.getRespDesc());
                            }
                        }
                    }
                    //进行中商户新增存量表
                    List<TMStatMfdCriteria> tmStatMfdCriteriaList = tmMcMchntInfoList.stream().map(this::convertMfdCriteria).collect(Collectors.toList());
                    allSmStatMfdCriteriaList.addAll(tmStatMfdCriteriaList);
                    rglog.info("进行中新增商户插入手续费达标统计表数据共<{}>条", tmStatMfdCriteriaList.size());
                    /* 取原纪录创建人和记录创建时间 */
                    for (TMMcMchntInfo tmMcMchntInfo : tmMcMchntInfoList) {
                        tmMcMchntInfo.setOprId(tmPlatBizTmpList.get(CommonConstant.ZERO).getOprId());
                        tmMcMchntInfo.setCreateTime(tmPlatBizTmpList.get(CommonConstant.ZERO).getCreateTime());
                        tmMcMchntInfo.setExitFlag(CommonConstant.MC_NOT_EXIT_FLAG);
                        tmMcMchntInfo.setNewMchntFlag(CommonConstant.MCHNT_OLD_FLAG);
                    }

                    /* 修改进行中正式表商户数据 */
                    returnCode = updateMcMchntInfoListByBank(tmMcMchntInfoList);
                    if (Database.DBS_SUCCESS != returnCode) {
                        rglog.error("更新机构<{}>商户手续费优惠类营销活动进行中新增商户数据失败!", globalInstId, globalMcNo);
                        dbsUtil.dbsEndTransaction(false);
                        throw new BizException(RespCodeEnum.SYSTEM_ERROR.getRespCode(), RespCodeEnum.SYSTEM_ERROR.getRespDesc());
                    }
                    //插入营销活动商户统计表数据
                    rglog.info("插入营销活动商户统计表数据共<{}>", tmStatMfdMchntList.size());
                    TMStatMfdMchntMapper tmStatMfdMchntMapper = new TMStatMfdMchntMapperImpl();
                    if (tmStatMfdMchntList.size() > 0) {
                        returnCode = tmStatMfdMchntMapper.insertNewStatMfdMchntData(tmStatMfdMchntList);
                        if (Database.DBS_SUCCESS != returnCode) {
                            rglog.error("插入机构<{}>营销活动商户统计表数据失败!", globalInstId, globalMcNo);
                            dbsUtil.dbsEndTransaction(false);
                            throw new BizException(RespCodeEnum.SYSTEM_ERROR.getRespCode(), RespCodeEnum.SYSTEM_ERROR.getRespDesc());
                        }
                    }

                }
                //查询活动下转移商户
                List<TMStatMfdCriteria> relationtmStatMfdCriteriaList = new ArrayList<>();
                List<TMMcMchntInfo> relationtmMcMchntInfoList = getAllMcMchntListInfoByinstIdMcMoFlag(CommonConstant.MC_TRANSFER_FLAG, CommonConstant.MCHNT_NEW_FLAG);
                if (null != relationtmMcMchntInfoList && relationtmMcMchntInfoList.size() > 0) {
                    flow = "0";
                    relationtmStatMfdCriteriaList = relationtmMcMchntInfoList.stream().map(this::convertMfdCriteria).collect(Collectors.toList());
                    allSmStatMfdCriteriaList.addAll(relationtmStatMfdCriteriaList);
                    //处理转移商户所在旧活动数据
                    chulitjb(dbsUtil);
                }
                rglog.info("插入手续费达标统计表数据共<{}>条,转移商户插入的数据共<{}>条", allSmStatMfdCriteriaList.size(), relationtmStatMfdCriteriaList.size());
                //插入手续费达标统计表数据
                TMStatMfdCriteriaMapper tmStatMfdCriteriaMapper = new TMStatMfdCriteriaMapperImpl();
                returnCode = tmStatMfdCriteriaMapper.insertNewMchntCriteriaData(allSmStatMfdCriteriaList);
                if (Database.DBS_SUCCESS != returnCode) {
                    rglog.error("插入手续费达标统计表数据失败!");
                    dbsUtil.dbsEndTransaction(false);
                    throw new BizException(RespCodeEnum.SYSTEM_ERROR.getRespCode(), RespCodeEnum.SYSTEM_ERROR.getRespDesc());
                }
                //查询上送活动号临时表信息
                TMPlatBizTmp tmPlatBizTmp1 = platBizTmpMapper.selectTmpMcInfo(publishMchntFeeDiscountMcRequest.getHeader().getInstId(), publishMchntFeeDiscountMcRequest.getMcNo(), TableNameEnum.T_M_MC_MFD_INFO.getTableNameCode());

                /* 解析商户手续费优惠类营销活动信息临时表预算数据并计算银行出资比例 */
                JsonTmpMfdMcInfo jsonTmpMfdMcInfo = (JsonTmpMfdMcInfo) JsonOperation.parseMcInfoTmpBizData1(rglog, tmPlatBizTmp1, TABLE_NAME);
                if (null == jsonTmpMfdMcInfo) {
                    rglog.error("解析机构<{}>商户手续费优惠类营销活动<{}>营销活动基本信息临时表数据失败!", globalInstId, globalMcNo);
                    dbsUtil.dbsEndTransaction(false);
                    throw new BizException(RespCodeEnum.SYSTEM_ERROR.getRespCode(), RespCodeEnum.SYSTEM_ERROR.getRespDesc());
                }

                TMMcMchntFeeDiscountInfo tmMcMchntFeeDiscountInfo1 = new TMMcMchntFeeDiscountInfo();
                tmMcMchntFeeDiscountInfo1.setInstId(globalInstId);
                tmMcMchntFeeDiscountInfo1.setMcNo(globalMcNo);
                tmMcMchntFeeDiscountInfo1.setAuditStatus(AuditStatusEnum.PUBLISH_AUDIT_PASSED.getAuditStatusCode());
                tmMcMchntFeeDiscountInfo1.setBudget(jsonTmpMfdMcInfo.getBudget());

                /* 更新营销活动预算数据 */
                returnCode = updateMcBudgetForPublishing(tmMcMchntFeeDiscountInfo1);
                if (Database.DBS_SUCCESS != returnCode) {
                    rglog.error("更新机构<{}>商户手续费优惠类营销活动<{}>营销活动基本信息预算数据失败!", globalInstId, globalMcNo);
                    dbsUtil.dbsEndTransaction(false);
                    throw new BizException(RespCodeEnum.SYSTEM_ERROR.getRespCode(), RespCodeEnum.SYSTEM_ERROR.getRespDesc());
                }
                int returnCodes = platBizTmpMapper.updataTMPlatBizByList(tmPlatBizTmpList, "publish");
                if (Database.DBS_SUCCESS != returnCodes) {
                    rglog.error("更新机构<{}>手续费减免类营销活动<{}>营销活动基本信息失败!", globalInstId, globalMcNo);
                    dbsUtil.dbsEndTransaction(false);
                    throw new BizException(RespCodeEnum.SYSTEM_ERROR.getRespCode(), RespCodeEnum.SYSTEM_ERROR.getRespDesc());
                }
            }
        } else {
            //判断批量任务是否处理成功，如果否直接拒掉
            /* 营销活动信息正式表查询 */
            McDetailInfoMapper mcDetailInfoMapper = new McDetailInfoMapperImpl();
            TMMcMchntFeeDiscountInfo tmMcMchntFeeDiscountInfo = (TMMcMchntFeeDiscountInfo) mcDetailInfoMapper.selectMcDetailInfo(globalInstId, globalMcNo, TableNameEnum.T_M_MC_MFD_INFO.getTableNameCode());
            if (null == tmMcMchntFeeDiscountInfo) {
                /* 异常结束数据库事务 */
                rglog.error("查询营销活动信息失败, INST_ID=<{}>, MC_NO=<{}>", globalInstId, globalMcNo);
                throw new BizException(RespCodeEnum.DATABASE_OPR_ERROR.getRespCode(), RespCodeEnum.DATABASE_OPR_ERROR.getRespDesc());
            }
            /**
             * 调整任务完成与否的判断逻辑，注册任务有两种情况
             * 1.未上传商户列表信息，此时批量先跑商户数据，然后再跑达标统计表数据
             * 2.上传商户列表信息，此时批量任务会跑达标统计表
             */
            if (tmMcMchntFeeDiscountInfo.getPublishBatchStatus().equals(CommonConstant.ZERO_COMMON_CONSTANT) && !CommonConstant.STOCK_MCHNT_FLAG_ZERO.equals(tmMcMchntFeeDiscountInfo.getStockMchntFlag())) {
                rglog.error("批量任务未处理成功, INST_ID=<{}>, MC_NO=<{}>", globalInstId, globalMcNo);
                throw new BizException(RespCodeEnum.FAILED_TO_RUN_TIME_TASK.getRespCode(), RespCodeEnum.FAILED_TO_RUN_TIME_TASK.getRespDesc());
            }
            if (tmMcMchntFeeDiscountInfo.getPublishBatchStatus().equals(CommonConstant.TWO_COMMON_CONSTANT) && !CommonConstant.STOCK_MCHNT_FLAG_ZERO.equals(tmMcMchntFeeDiscountInfo.getStockMchntFlag())) {
                rglog.error("批量任务处理失败, INST_ID=<{}>, MC_NO=<{}>", globalInstId, globalMcNo);
                throw new BizException(RespCodeEnum.TIME_TASK_RUN_FAILED.getRespCode(), RespCodeEnum.TIME_TASK_RUN_FAILED.getRespDesc());
            }
            /* 若营销活动状态为未发布，需要更新商户手续费优惠类营销活动信息表的营销活动状态和审批状态 */

            /* 更新正式表营销活动状态和审批状态 */
            TMMcMchntFeeDiscountInfo tmMcMchntFeeDiscountInfo1 = new TMMcMchntFeeDiscountInfo();
            tmMcMchntFeeDiscountInfo1.setInstId(globalInstId);
            tmMcMchntFeeDiscountInfo1.setMcNo(globalMcNo);
            tmMcMchntFeeDiscountInfo1.setMcStatus(McStatusEnum.PROGRESSING.getMcStatusCode());
            tmMcMchntFeeDiscountInfo1.setAuditStatus(AuditStatusEnum.PUBLISH_AUDIT_PASSED.getAuditStatusCode());
            tmMcMchntFeeDiscountInfo1.setLastOprId(globalOprId);
            tmMcMchntFeeDiscountInfo1.setUpdateTime(globalTimeStamp);
            returnCode = updateMcStatusForPublishing(tmMcMchntFeeDiscountInfo1);
            if (Database.DBS_SUCCESS != returnCode) {
                rglog.error("发布成功更新商户手续费优惠类营销活动信息表失败！RETURN_CODE=<{}>", returnCode);
                dbsUtil.dbsEndTransaction(false);
                throw new BizException(RespCodeEnum.SYSTEM_ERROR.getRespCode(), RespCodeEnum.SYSTEM_ERROR.getRespDesc());
            }
        }

        /* 更新业务数据临时表状态 */
        TMPlatBizTmp tmPlatBizTmp1 = new TMPlatBizTmp();
        tmPlatBizTmp1.setInstId(globalInstId);
        tmPlatBizTmp1.setMcNo(globalMcNo);
        tmPlatBizTmp1.setBizOpr(BizOprEnum.PUBLISH.getBizOprCode());
        tmPlatBizTmp1.setMcStatus(McStatusEnum.PROGRESSING.getMcStatusCode());
        tmPlatBizTmp1.setAuditStatus(AuditStatusEnum.PUBLISH_AUDIT_PASSED.getAuditStatusCode());
        returnCode = updateSingleMcInfoForPublishing(tmPlatBizTmp1);
        if (Database.DBS_SUCCESS != returnCode) {
            rglog.error("发布成功更新业务数据临时表失败！RETURN_CODE=<{}>", returnCode);
            dbsUtil.dbsEndTransaction(false);
            throw new BizException(RespCodeEnum.SYSTEM_ERROR.getRespCode(), RespCodeEnum.SYSTEM_ERROR.getRespDesc());
        }

        dbsUtil.dbsEndTransaction(true);
    }

    /**
     * 营销活动发布拒绝流程
     *
     * @param xmlTreeUtil                      内部XML树
     * @param publishMchntFeeDiscountMcRequest 商户手续费优惠类活动发布接口请求对象
     * @throws Exception 异常信息
     * @author Jinan Liu
     * @date 2020/5/26 00:50
     */
    private void refusePublishMc(XmlTreeUtil xmlTreeUtil, PublishMchntFeeDiscountMcRequest publishMchntFeeDiscountMcRequest) throws Exception {

        int returnCode;

        /* 开启数据库事务 */
        String dbPoolName = XmlConfigUtil.getXmlConfigCacheKeyValue(AppConfigConstant.DATABASE_CONF_NODE, AppConfigConstant.MOMP_POOL_NAME);
        String corporation = xmlTreeUtil.getXmlTreeStringValue(AppParamConstant.CORPORATION);
        if (null != corporation && !corporation.isEmpty()) {
            String dbPoolCashNode = corporation.trim() + AppParamConstant.DATABASE_CONF_NODE;
            dbPoolName = XmlConfigUtil.getXmlConfigCacheKeyValue(dbPoolCashNode, AppConfigConstant.MOMP_POOL_NAME);
        }
        DbsUtil dbsUtil = new DbsUtil(dbPoolName);
        dbsUtil.dbsBeginTransaction();

        /* 更新临时表状态 */
        if (!McStatusEnum.PROGRESSING.getMcStatusCode().equals(this.mcStatus)) {
            TMPlatBizTmp tmPlatBizTmp = new TMPlatBizTmp();
            tmPlatBizTmp.setInstId(globalInstId);
            tmPlatBizTmp.setMcNo(globalMcNo);
            tmPlatBizTmp.setBizStatus(BizStatusEnum.NORMAL_STATUS.getBizStatusCode());
            tmPlatBizTmp.setMcStatus(McStatusEnum.NOT_PUBLISHED.getMcStatusCode());
            tmPlatBizTmp.setBizOpr(BizOprEnum.RETURN.getBizOprCode());
            tmPlatBizTmp.setAuditRefuseReason(publishMchntFeeDiscountMcRequest.getOprContent());
            tmPlatBizTmp.setAuditStatus(AuditStatusEnum.PUBLISH_AUDIT_REJECT.getAuditStatusCode());
            tmPlatBizTmp.setLastOprId(globalOprId);
            tmPlatBizTmp.setLastUpdateTime(globalTimeStamp);
            returnCode = updateMcAuditStatusForPublishingRefusal(tmPlatBizTmp);
            if (Database.DBS_SUCCESS != returnCode) {
                rglog.error("发布失败更新业务数据临时表失败！RETURN_CODE=<{}>", returnCode);
                dbsUtil.dbsEndTransaction(false);
                throw new BizException(RespCodeEnum.SYSTEM_ERROR.getRespCode(), RespCodeEnum.SYSTEM_ERROR.getRespDesc());
            }
        }

        /* 进行中的活动只更新临时表数据 */
        if (McStatusEnum.NOT_PUBLISHED.getMcStatusCode().equals(this.mcStatus)) {
            rglog.info("PublishMchntFeeDiscountMcService.refusePublishMc");
            //判断批量任务是否处理成功，如果否直接拒掉
            if (this.tmMcMchntFeeDiscountInfo.getPublishBatchStatus().equals(CommonConstant.ZERO_COMMON_CONSTANT) && !CommonConstant.STOCK_MCHNT_FLAG_ZERO.equals(tmMcMchntFeeDiscountInfo.getStockMchntFlag())) {
                rglog.error("批量任务未处理成功, INST_ID=<{}>, MC_NO=<{}>", globalInstId, globalMcNo);
                dbsUtil.dbsEndTransaction(false);
                throw new BizException(RespCodeEnum.FAILED_TO_RUN_TIME_TASK.getRespCode(), RespCodeEnum.FAILED_TO_RUN_TIME_TASK.getRespDesc());
            }
            if (this.tmMcMchntFeeDiscountInfo.getPublishBatchStatus().equals(CommonConstant.TWO_COMMON_CONSTANT) && !CommonConstant.STOCK_MCHNT_FLAG_ZERO.equals(tmMcMchntFeeDiscountInfo.getStockMchntFlag())) {
                rglog.error("批量任务处理失败, INST_ID=<{}>, MC_NO=<{}>", globalInstId, globalMcNo);
                dbsUtil.dbsEndTransaction(false);
                throw new BizException(RespCodeEnum.TIME_TASK_RUN_FAILED.getRespCode(), RespCodeEnum.TIME_TASK_RUN_FAILED.getRespDesc());
            }
            //查询打款记录表是否有记录
            TMMcFundInfoMapper tmMcFundInfoMapper = new TMMcFundInfoMapperImpl();
            TMMcFundInfo tmMcFundInfo = new TMMcFundInfo();
            tmMcFundInfo.setInstId(globalInstId);
            tmMcFundInfo.setMcNo(globalMcNo);
            int code = tmMcFundInfoMapper.checkMaxmiumRecordIndexInfoByInstIdMcNo(tmMcFundInfo);
            //code大于0 存在打款成功的记录 不允许
            if (code > CommonConstant.ZERO) {
                dbsUtil.dbsEndTransaction(false);
                rglog.info("存在打款成功的记录，不允许发布拒绝退回");
                throw new BizException(RespCodeEnum.MC_FUND_SUCCESS_NOT_ALLOWED_TO_REFUSE_PUBLISH.getRespCode(), RespCodeEnum.MC_FUND_SUCCESS_NOT_ALLOWED_TO_REFUSE_PUBLISH.getRespDesc());
            }
            TMMcMchntFeeDiscountInfo tmMcMchntFeeDiscountInfo = new TMMcMchntFeeDiscountInfo();
            tmMcMchntFeeDiscountInfo.setInstId(globalInstId);
            tmMcMchntFeeDiscountInfo.setMcNo(globalMcNo);
            tmMcMchntFeeDiscountInfo.setMcStatus(McStatusEnum.NOT_PUBLISHED.getMcStatusCode());
            tmMcMchntFeeDiscountInfo.setAuditStatus(AuditStatusEnum.PUBLISH_AUDIT_REJECT.getAuditStatusCode());
            tmMcMchntFeeDiscountInfo.setPublishRefuseReason(publishMchntFeeDiscountMcRequest.getOprContent());
            tmMcMchntFeeDiscountInfo.setLastOprId(globalOprId);
            tmMcMchntFeeDiscountInfo.setUpdateTime(globalTimeStamp);
            returnCode = updateMcAuditStatusForPublishRefusal(tmMcMchntFeeDiscountInfo);
            if (Database.DBS_SUCCESS != returnCode) {
                rglog.error("发布失败更新商户手续费优惠类营销活动信息表失败！RETURN_CODE=<{}>", returnCode);
                dbsUtil.dbsEndTransaction(false);
                throw new BizException(RespCodeEnum.SYSTEM_ERROR.getRespCode(), RespCodeEnum.SYSTEM_ERROR.getRespDesc());
            }
        } else if (McStatusEnum.PROGRESSING.getMcStatusCode().equals(this.mcStatus)) {
            PlatBizTmpMapper platBizTmpMapper = new PlatBizTmpMapperImpl();
            //更新临时表活动状态为发布拒绝
            TMPlatBizTmp tmPlatBizTmp = new TMPlatBizTmp();
            tmPlatBizTmp.setBizStatus(BizStatusEnum.NORMAL_STATUS.getBizStatusCode());
            tmPlatBizTmp.setMcStatus(McStatusEnum.NOT_PUBLISHED.getMcStatusCode());
            tmPlatBizTmp.setOprTableEname(TableNameEnum.T_M_MC_MFD_INFO.getTableNameCode());
            tmPlatBizTmp.setOprTableCname(TableNameEnum.T_M_MC_MFD_INFO.getTableNameDesc());
            tmPlatBizTmp.setAuditStatus(AuditStatusEnum.PUBLISH_AUDIT_REJECT.getAuditStatusCode());
            returnCode = platBizTmpMapper.updataTMPlatBizByinstIdMcNoTableNameAuditStatus(globalInstId, globalMcNo, tmPlatBizTmp, AuditStatusEnum.PUBLISH_AUDIT_PROCESSING.getAuditStatusCode(), "", "");
            if (cc.rengu.utility.dbs.Database.DBS_SUCCESS != returnCode) {
                /* 营销活动临时数据审批状态异常，不可审批通过 */
                dbsUtil.dbsEndTransaction(false);
                rglog.error("{}, RETURN_CODE=<{}>, MC_NO=<{}>", RespCodeEnum.DATABASE_OPR_ERROR.getRespDesc(), returnCode, globalMcNo);
                throw new BizException(RespCodeEnum.DATABASE_OPR_ERROR.getRespCode(), RespCodeEnum.DATABASE_OPR_ERROR.getRespDesc());
            }
            tmPlatBizTmp.setOprTableCname(TableNameEnum.T_M_MC_MCHNT_INFO.getTableNameDesc());
            tmPlatBizTmp.setOprTableEname(TableNameEnum.T_M_MC_MCHNT_INFO.getTableNameCode());
            returnCode = platBizTmpMapper.updataTMPlatBizByinstIdMcNoTableNameAuditStatus(globalInstId, globalMcNo, tmPlatBizTmp, AuditStatusEnum.PUBLISH_AUDIT_PROCESSING.getAuditStatusCode(), "", "");
            if (cc.rengu.utility.dbs.Database.DBS_SUCCESS != returnCode && cc.rengu.utility.dbs.Database.DBS_NOT_FOUND != returnCode) {
                /* 营销活动临时数据审批状态异常，不可审批通过 */
                dbsUtil.dbsEndTransaction(false);
                rglog.error("{}, RETURN_CODE=<{}>, MC_NO=<{}>", RespCodeEnum.DATABASE_OPR_ERROR.getRespDesc(), returnCode, globalMcNo);
                throw new BizException(RespCodeEnum.DATABASE_OPR_ERROR.getRespCode(), RespCodeEnum.DATABASE_OPR_ERROR.getRespDesc());
            }
            //更新商户手续费优惠类活动为发布拒绝状态
            TMMcMchntFeeDiscountInfo tmMcMchntFeeDiscountInfo = new TMMcMchntFeeDiscountInfo();
            tmMcMchntFeeDiscountInfo.setInstId(globalInstId);
            tmMcMchntFeeDiscountInfo.setMcNo(globalMcNo);
            tmMcMchntFeeDiscountInfo.setRemark1(AuditStatusEnum.PUBLISH_AUDIT_PROCESSING.getAuditStatusCode());
            tmMcMchntFeeDiscountInfo.setMcStatus(McStatusEnum.PROGRESSING.getMcStatusCode());

            tmMcMchntFeeDiscountInfo.setAuditStatus(AuditStatusEnum.PUBLISH_AUDIT_REJECT.getAuditStatusCode());
            tmMcMchntFeeDiscountInfo.setPublishRefuseReason(publishMchntFeeDiscountMcRequest.getOprContent());
            tmMcMchntFeeDiscountInfo.setLastOprId(globalOprId);
            tmMcMchntFeeDiscountInfo.setUpdateTime(globalTimeStamp);

            returnCode = updateMcAuditStatusForPublishRefusal(tmMcMchntFeeDiscountInfo);
            if (Database.DBS_SUCCESS != returnCode) {
                rglog.error("发布失败更新商户手续费减免类营销活动信息表失败！RETURN_CODE=<{}>", returnCode);
                dbsUtil.dbsEndTransaction(false);
                throw new BizException(RespCodeEnum.SYSTEM_ERROR.getRespCode(), RespCodeEnum.SYSTEM_ERROR.getRespDesc());
            }
            //查询营销商户表数据
            McMchntInfoMapper mcMchntInfoMapper = new McMchntInfoMapperImpl();
            List<TMMcMchntInfo> tmMcMchntInfoList = getAllMcMchntListInfoByinstIdMcMoFlag(CommonConstant.MC_EXIT_FLAG, CommonConstant.MCHNT_NEW_FLAG);
            if (null != tmMcMchntInfoList && tmMcMchntInfoList.size() > 0) {
                for (TMMcMchntInfo tmMcMchntInfo : tmMcMchntInfoList) {
                    tmMcMchntInfo.setNewMchntFlag(CommonConstant.MCHNT_REFUSE_FLAG);
                }
                returnCode = mcMchntInfoMapper.updateMcMchntInfoListByBank(tmMcMchntInfoList);
                if (cc.rengu.utility.dbs.Database.DBS_SUCCESS != returnCode) {
                    /* 营销活动审批状态异常，不可审批通过 */
                    dbsUtil.dbsEndTransaction(false);
                    rglog.error("{}, RETURN_CODE=<{}>, MC_NO=<{},营销活动商户正式表数据更新失败>", RespCodeEnum.WRONG_UPDATEMCMCHNT_ERROR.getRespDesc(), returnCode, globalMcNo);
                    throw new BizException(RespCodeEnum.WRONG_UPDATEMCMCHNT_ERROR.getRespCode(), RespCodeEnum.WRONG_UPDATEMCMCHNT_ERROR.getRespDesc());
                }
            }
        }

        dbsUtil.dbsEndTransaction(true);
    }

    /**
     * 发布成功更新临时表营销活动数据的状态、营销活动状态和审批状态
     *
     * @param tmPlatBizTmp 业务数据临时表
     * @return int 返回码
     * @throws Exception 异常信息
     * @author Jinan Liu
     * @date 2020/5/25 22:33
     */
    private int updateSingleMcInfoForPublishing(TMPlatBizTmp tmPlatBizTmp) throws Exception {

        PlatBizTmpMapper platBizTmpMapper = new PlatBizTmpMapperImpl();
        return platBizTmpMapper.updateSingleMcInfoForPublishing(tmPlatBizTmp);
    }

    /**
     * 发布成功更新整事表营销活动的营销活动状态和审批状态
     *
     * @param tmMcMchntFeeDiscountInfo 商户手续费优惠类营销活动信息表
     * @return int 返回码
     * @throws Exception 异常信息
     * @author Jinan Liu
     * @date 2020/5/25 22:45
     */
    private int updateMcStatusForPublishing(TMMcMchntFeeDiscountInfo tmMcMchntFeeDiscountInfo) throws Exception {

        McDetailInfoMapper mcDetailInfoMapper = new McDetailInfoMapperImpl();
        return mcDetailInfoMapper.updateMcStatusForPublishing(tmMcMchntFeeDiscountInfo, TABLE_NAME);
    }

    /**
     * 取待提交发布营销活动商户规则临时表中待提交发布的商户数据
     *
     * @param tmPlatBizTmp 业务数据临时表
     * @return java.util.List<cc.rengu.igas.momp.common.entity.TMPlatBizTmp> 业务数据临时表
     * @throws Exception 异常信息
     * @author Jinan Liu
     * @date 2020/5/25 23:07
     */
    private List<TMPlatBizTmp> selectNewAddedMchntInfoForPublishing(TMPlatBizTmp tmPlatBizTmp) throws Exception {
        List<Object> tmMcMchntInfoList = new ArrayList<>();
        PageInfo pageInfo = new PageInfo();
        int i = 0;
        pageInfo.setPageIndex(i);
        pageInfo.setPageSize(9999);
        PlatBizTmpMapper platBizTmpMapper = new PlatBizTmpMapperImpl();
        PageResult tmMcMchntInfoPageInfo = platBizTmpMapper.selectNewAddedMchntInfoForPublishing(tmPlatBizTmp, pageInfo);
        if (null != tmMcMchntInfoPageInfo && null != tmMcMchntInfoPageInfo.getResult()) {
            tmMcMchntInfoList.addAll(tmMcMchntInfoPageInfo.getResult());
        }
        while (null != tmMcMchntInfoPageInfo && null != tmMcMchntInfoPageInfo.getResult() && tmMcMchntInfoPageInfo.getResult().size() >= 1) {
            i++;
            pageInfo.setPageIndex(i);
            tmMcMchntInfoPageInfo = platBizTmpMapper.selectNewAddedMchntInfoForPublishing(tmPlatBizTmp, pageInfo);
            if (null != tmMcMchntInfoPageInfo && null != tmMcMchntInfoPageInfo.getResult()) {
                tmMcMchntInfoList.addAll(tmMcMchntInfoPageInfo.getResult());
            }
        }
        List<TMPlatBizTmp> mcMchntInfoList = tmMcMchntInfoList.stream().map(item -> (TMPlatBizTmp) (item)).collect(Collectors.toList());
        return mcMchntInfoList;
    }

    /**
     * 将临时表新增商户数据插入正式表
     *
     * @param tmMcMchntInfoList 营销活动商户信息表
     * @return int 返回码
     * @throws Exception 异常信息
     * @author Jinan Liu
     * @date 2020/5/26 00:16
     */
    private int insertMcMchntInfoListByBank(List<TMMcMchntInfo> tmMcMchntInfoList) throws Exception {

        McMchntInfoMapper mcMchntInfoMapper = new McMchntInfoMapperImpl();
        return mcMchntInfoMapper.insertMcMchntInfoListByBank(tmMcMchntInfoList);
    }

    /**
     * 活动中中添加商户流程发布成功更新商户手续费优惠类营销活动预算数据
     *
     * @param tmMcMchntFeeDiscountInfo 商户手续费优惠类营销活动信息表
     * @return int 返回码
     * @throws Exception 异常信息
     * @author Jinan Liu
     * @date 2020/5/26 00:23
     */
    private int updateMcBudgetForPublishing(TMMcMchntFeeDiscountInfo tmMcMchntFeeDiscountInfo) throws Exception {

        McDetailInfoMapper mcDetailInfoMapper = new McDetailInfoMapperImpl();
        return mcDetailInfoMapper.updateMcBudgetForPublishing(tmMcMchntFeeDiscountInfo);
    }

    /**
     * 发布拒绝更新正式表商户手续费优惠类营销活动审批状态和发布拒绝原因
     *
     * @param tmMcMchntFeeDiscountInfo 商户手续费优惠类营销活动信息表
     * @return int 返回码
     * @throws Exception 异常信息
     * @author Jinan Liu
     * @date 2020/5/26 01:02
     */
    private int updateMcAuditStatusForPublishRefusal(TMMcMchntFeeDiscountInfo tmMcMchntFeeDiscountInfo) throws Exception {

        McDetailInfoMapper mcDetailInfoMapper = new McDetailInfoMapperImpl();
        return mcDetailInfoMapper.updateMcAuditStatusForPublishRefusal(tmMcMchntFeeDiscountInfo, TABLE_NAME);
    }

    /**
     * 发布拒绝更新临时表商户手续费优惠类营销活动审批状态和发布拒绝原因
     *
     * @param tmPlatBizTmp 业务数据临时表
     * @return int 返回码
     * @throws Exception 异常信息
     * @author Jinan Liu
     * @date 2020/5/26 01:12
     */
    private int updateMcAuditStatusForPublishingRefusal(TMPlatBizTmp tmPlatBizTmp) throws Exception {

        PlatBizTmpMapper platBizTmpMapper = new PlatBizTmpMapperImpl();
        return platBizTmpMapper.updateMcAuditStatusForPublishingRefusal(tmPlatBizTmp);
    }

    /**
     * 更新商户数据正式表
     *
     * @param tmMcMchntInfoList 营销活动商户信息表
     * @return int 返回码
     * @throws Exception 异常信息
     * @author Jinan Liu
     * @date 2020/5/26 00:16
     */
    private int updateMcMchntInfoListByBank(List<TMMcMchntInfo> tmMcMchntInfoList) throws Exception {

        McMchntInfoMapper mcMchntInfoMapper = new McMchntInfoMapperImpl();
        return mcMchntInfoMapper.updateMcMchntInfoListByBank(tmMcMchntInfoList);
    }

    /**
     * 判断未上送商户号商圈号时，机构下的非特殊费率商户达标统计表是否存该交易日期内的数据
     *
     * @param publishMchntFeeDiscountMcRequest
     */
    private void checkMchntNoAndAreaNo(XmlTreeUtil xmlTreeUtil, PublishMchntFeeDiscountMcRequest publishMchntFeeDiscountMcRequest) throws Exception {
        MchntInfoMapper mchntInfoMapper = new MchntInfoMapperImpl();
        McMchntInfoMapper mcMchntInfoMapper = new McMchntInfoMapperImpl();
        McOrgInfoMapper mcOrgInfoMapper = new McOrgInfoMapperImpl();
        //查询该营销活动基本信息
        McDetailInfoMapper mcDetailInfoMapper = new McDetailInfoMapperImpl();
        MfdMcListInfoInObj mfdMcListInfoInObj = new MfdMcListInfoInObj();
        mfdMcListInfoInObj.setInstId(globalInstId);
        mfdMcListInfoInObj.setMcNo(globalMcNo);
        mfdMcListInfoInObj.setOrgId(publishMchntFeeDiscountMcRequest.getQueryOrgId());
        TMMcMchntFeeDiscountInfo tmMcMchntFeeDiscountInfo = mcDetailInfoMapper.selectMfdMcDetailInfoByBankBasicRole(mfdMcListInfoInObj);
        //如果营销活动不是进行中状态
        if (!tmMcMchntFeeDiscountInfo.getMcStatus().equals(McStatusEnum.PROGRESSING.getMcStatusCode())) {
            /* 开启数据库事务 */
            String dbPoolName = XmlConfigUtil.getXmlConfigCacheKeyValue(AppConfigConstant.DATABASE_CONF_NODE, AppConfigConstant.MOMP_POOL_NAME);
            String corporation = xmlTreeUtil.getXmlTreeStringValue(AppParamConstant.CORPORATION);
            if (null != corporation && !corporation.isEmpty()) {
                String dbPoolCashNode = corporation.trim() + AppParamConstant.DATABASE_CONF_NODE;
                dbPoolName = XmlConfigUtil.getXmlConfigCacheKeyValue(dbPoolCashNode, AppConfigConstant.MOMP_POOL_NAME);
            }
            DbsUtil dbsUtil = new DbsUtil(dbPoolName);
            dbsUtil.dbsBeginTransaction();
            //获取当前时间
            String date = DateUtil.getCurrentDate();
            //查询营销活动商户信息
            List<TMMcMchntInfo> tmMcMchntInfoList = getAllMcMchntListInfo();
            if (tmMcMchntFeeDiscountInfo.getStockMchntFlag().equals(CommonConstant.STOCK_MCHNT_FLAG_ONE)) {
                if (null != tmMcMchntInfoList && tmMcMchntInfoList.size() > 0) {
                    for (TMMcMchntInfo tmMcMchntInfo : tmMcMchntInfoList) {
                        //查询手续费达标统计表是否有该商户现交易日期达标的数据
                        TMStatMfdCriteriaMapper tmStatMfdCriteriaMapper = new TMStatMfdCriteriaMapperImpl();
                        TMStatMfdCriteria tmStatMfdCriteria = tmStatMfdCriteriaMapper.selectTMStatMfdCriteriaByUsingMchntNoAndDateRange(globalInstId, tmMcMchntInfo.getMchntNo(), date);
                        //如果达标统计表有当前交易日期商户达标的数据，则直接拒绝新增
                        if (null != tmStatMfdCriteria) {
                            /* 营销活动信息正式表查询 */
                            TMMcMchntFeeDiscountInfo tmMcMchntFeeDiscountInfo1 = (TMMcMchntFeeDiscountInfo) mcDetailInfoMapper.selectMcDetailInfo(globalInstId, tmStatMfdCriteria.getMcNo(), TABLE_NAME);
                            if (null != tmStatMfdCriteria && (null == tmMcMchntFeeDiscountInfo1 || tmMcMchntFeeDiscountInfo1.getMcStatus().equals(McStatusEnum.ENDED.getMcStatusCode()) || tmMcMchntFeeDiscountInfo1.getMcStatus().equals(McStatusEnum.FORCE_ENDED.getMcStatusCode()) || tmMcMchntFeeDiscountInfo1.getMcStatus().equals(McStatusEnum.ALL_ENDED.getMcStatusCode()))) {
                                rglog.error("交易流水号：<{}>, 商户<{}>已参加其他手续费活动！", publishMchntFeeDiscountMcRequest.getHeader().getTraceNo(), tmMcMchntInfo.getMchntNo());
                                throw new BizException(RespCodeEnum.WRONG_MCHNT_ISALREADY_ORTHER_INMC_ERROR.getRespCode(), RespCodeEnum.WRONG_MCHNT_ISALREADY_ORTHER_INMC_ERROR.getRespDesc());
                            }
                        }
                    }
                }

            } else if (tmMcMchntFeeDiscountInfo.getStockMchntFlag().equals(CommonConstant.STOCK_MCHNT_FLAG_TWO)) {
                //查询营销活动机构信息
                List<TMMcOrgInfo> orgInfoList = mcOrgInfoMapper.selectMcOrgInfoList(globalInstId, globalMcNo);
                OrganizationMapper organizationMapper = new OrganizationMapperImpl();
                //处理接口请求上送的机构信息
                List<String> requestOrgIdList = orgInfoList.stream().map(item -> item.getOrgId()).collect(Collectors.toList());
                //对请求上送的机构进行去重处理
                requestOrgIdList = requestOrgIdList.stream().distinct().collect(Collectors.toList());

                //需要从接口上送的机构信息中移除的机构
                List<String> removeOrgIdList = new ArrayList<>();
                List<String> requestResultOrgList = new ArrayList<>();

                String queryOrgId = publishMchntFeeDiscountMcRequest.getQueryOrgId();

                //查询当前登录用户的所属机构信息
                Organization queryOrgInfo = organizationMapper.selectOrganization(globalInstId, queryOrgId);

                //当前登录用户所属机构的最大深度
                int orgLevealDepth = 5;
                while (orgLevealDepth > 0) {
                    if (null != queryOrgInfo) {
                        String superOrgId = queryOrgInfo.getSuperOrgCode();
                        String orgLevel = queryOrgInfo.getOrgLevel();
                        rglog.info("交易流水号：<{}>,当前机构机构编码<{}>,上级机构编码<{}>,机构编码级别<{}>", publishMchntFeeDiscountMcRequest.getHeader().getTraceNo(), queryOrgInfo.getOrgCode(), orgLevel);

                        if (null != superOrgId && !"00".equals(orgLevel)) {
                            removeOrgIdList.add(superOrgId);
                            rglog.info("交易流水号：<{}>,接口请求上送的机构<{}>需要去除!", publishMchntFeeDiscountMcRequest.getHeader().getTraceNo(), superOrgId);
                            queryOrgInfo = organizationMapper.selectOrganization(globalInstId, superOrgId);
                        } else {
                            break;
                        }
                        orgLevealDepth--;
                    } else {
                        rglog.error("交易流水号：<{}>, 机构<{}>机构信息查询失败！", publishMchntFeeDiscountMcRequest.getHeader().getTraceNo(), removeOrgIdList.size(), queryOrgId);
                        throw new BizException(RespCodeEnum.NO_ORG_INFO_ERROR.getRespCode(), RespCodeEnum.NO_ORG_INFO_ERROR.getRespDesc());
                    }
                }

                if (null != removeOrgIdList && !removeOrgIdList.isEmpty()) {
                    rglog.info("交易流水号：<{}>, 接口上送的机构机构信息中有<{}>个不能参加活动（操作员所属机构的上属机构不能参加）", publishMchntFeeDiscountMcRequest.getHeader().getTraceNo(), removeOrgIdList.size());
                    requestResultOrgList = requestOrgIdList.stream().filter(item -> !removeOrgIdList.contains(item)).collect(Collectors.toList());
                } else {
                    requestResultOrgList = requestOrgIdList;
                }
                //上送机构下所有商户
                List<TBMchntBaseInfo> newAlltbMchntBaseInfoList = new ArrayList<>();
                //循环查询机构下所有商户信息
                for (int i = 0; i < requestResultOrgList.size(); i++) {
                    List<TBMchntBaseInfo> tbMchntBaseInfoList = mchntInfoMapper.selectMchntBaseInfoListBySignInstId(globalInstId, requestResultOrgList.get(i));
                    if (null != tbMchntBaseInfoList && tbMchntBaseInfoList.size() > 0) {
                        newAlltbMchntBaseInfoList.addAll(tbMchntBaseInfoList);
                    }
                }
                //不包含特殊费率商户的list
                List<TBMchntBaseInfo> newtbMchntBaseInfoList = new ArrayList<>();
                for (TBMchntBaseInfo tbMchntBaseInfo : newAlltbMchntBaseInfoList) {
                    //判断商户是否存在特殊费率
                    List<TBMchntFeeInfo> tbMchntFeeInfoList = mchntInfoMapper.selectMchntFeeInfoListByMchntNo(globalInstId, tbMchntBaseInfo.getMchntNo());
                    if (null != tbMchntFeeInfoList && tbMchntFeeInfoList.size() > 0) {
                        tbMchntFeeInfoList = tbMchntFeeInfoList.stream().filter(item -> item.getFeeInputMode().equals(CommonConstant.ZERO_COMMON_CONSTANT)).collect(Collectors.toList());
                        if (null == tbMchntFeeInfoList || tbMchntFeeInfoList.size() == 0) {
                            newtbMchntBaseInfoList.add(tbMchntBaseInfo);
                        } else {
                            continue;
                        }
                    }
                    //查询手续费达标统计表是否有该商户现交易日期达标的数据
                    TMStatMfdCriteriaMapper tmStatMfdCriteriaMapper = new TMStatMfdCriteriaMapperImpl();
                    TMStatMfdCriteria tmStatMfdCriteria = tmStatMfdCriteriaMapper.selectTMStatMfdCriteriaByUsingMchntNoAndDateRange(globalInstId, tbMchntBaseInfo.getMchntNo(), date);
                    //如果达标统计表有当前交易日期商户达标的数据，则直接拒绝新增
                    if (null != tmStatMfdCriteria) {
                        rglog.error("交易流水号：<{}>, 商户<{}>已参加其他手续费活动！", publishMchntFeeDiscountMcRequest.getHeader().getTraceNo(), tbMchntBaseInfo.getMchntNo());
                        throw new BizException(RespCodeEnum.WRONG_MCHNT_ISALREADY_ORTHER_INMC_ERROR.getRespCode(), RespCodeEnum.WRONG_MCHNT_ISALREADY_ORTHER_INMC_ERROR.getRespDesc());
                    }
                }
                //判断是否有新增达标的商户
                if (null != newtbMchntBaseInfoList && newtbMchntBaseInfoList.size() > 0) {
                    //比较营销活动商户表与机构下达标商户 取出未插入营销活动商户表的商户信息
                    for (TMMcMchntInfo tmMcMchntInfo : tmMcMchntInfoList) {
                        newtbMchntBaseInfoList = newtbMchntBaseInfoList.stream().filter(item -> !item.getMchntNo().equals(tmMcMchntInfo.getMchntNo())).collect(Collectors.toList());
                    }
                    //如果存在未插入营销活动商户表的商户信息，则插入营销活动商户表
                    if (null != newtbMchntBaseInfoList && newtbMchntBaseInfoList.size() > 0) {
                        List<TMMcMchntInfo> newtmMcMchntInfoList = newtbMchntBaseInfoList.stream().map(this::convertMcMchntInfoByBaseInfo).collect(Collectors.toList());
                        int returnCode = mcMchntInfoMapper.insertMcMchntInfoListByBank(tmMcMchntInfoList);
                        if (returnCode != cc.rengu.utility.dbs.Database.DBS_SUCCESS) {
                            /* 异常结束数据库事务 */
                            rglog.error("新增营销活动商户信息失败, RETURN_CODE=<{}>, MC_NO=<{}>", returnCode, globalMcNo);
                            dbsUtil.dbsEndTransaction(false);
                            throw new BizException(RespCodeEnum.DATABASE_OPR_ERROR.getRespCode(), RespCodeEnum.DATABASE_OPR_ERROR.getRespDesc());
                        }
                    }
                }
            }
        }
    }

    /**
     * 营销活动商户信息数据库实体类和接口实体类数据转换
     *
     * @param tbMchntBaseInfo 商户基本信息表
     * @return cc.rengu.igas.momp.common.entity.TBMchntBaseInfo 商户基本信息表
     * @author JL Pang
     * @since 2020/4/1 21:10
     */
    private TMMcMchntInfo convertMcMchntInfoByBaseInfo(TBMchntBaseInfo tbMchntBaseInfo) {
        TMMcMchntInfo mcMchntInfo = new TMMcMchntInfo();
        try {
            /* 法人机构号 */
            mcMchntInfo.setInstId(globalInstId);
            /* 营销活动编号 */
            mcMchntInfo.setMcNo(globalMcNo);
            /* 商户范围类型 */
            mcMchntInfo.setMchntType(tbMchntBaseInfo.getMchntType());
            /* 商户范围号 */
            mcMchntInfo.setMchntNo(tbMchntBaseInfo.getMchntNo());
            /* 商户范围名称 */
            mcMchntInfo.setMchntName(tbMchntBaseInfo.getMchntName());
            /* 新增商户标志 */
            mcMchntInfo.setNewMchntFlag(CommonConstant.MCHNT_OLD_FLAG);
            /* 退出标志 */
            mcMchntInfo.setExitFlag(CommonConstant.MC_NOT_EXIT_FLAG);
            /* 达标日期 */
            mcMchntInfo.setQualifiedDate(globalTxnDate);
            /* 创建人 */
            mcMchntInfo.setOprId(globalOprId);
            /* 创建时间 */
            mcMchntInfo.setCreateTime(globalTimeStamp);

        } catch (Exception e) {
            rglog.error("转换营销活动商户信息异常,异常信息:<{}>", StringUtil.ExceptionToString(e));
            throw new BizException(RespCodeEnum.SYSTEM_ERROR.getRespCode(), RespCodeEnum.SYSTEM_ERROR.getRespDesc());
        }

        return mcMchntInfo;
    }

    /**
     * 营销活动商户信息数据库实体类和手续费达标统计表接口实体类数据转换
     *
     * @param tmMcMchntInfo 商户基本信息表
     * @return cc.rengu.igas.momp.common.entity.TMMcMchntInfo 商户基本信息表
     * @author JL Pang
     * @since 2020/8/3 21:10
     */
    private TMStatMfdCriteria convertMfdCriteria(TMMcMchntInfo tmMcMchntInfo) {
        //查询手续费达标统计表是否有该商户现交易日期达标的数据
        TMStatMfdCriteriaMapper tmStatMfdCriteriaMapper = new TMStatMfdCriteriaMapperImpl();
        TMStatMfdCriteria tmStatMfdCriterias = null;
        try {
            tmStatMfdCriterias = tmStatMfdCriteriaMapper.selectTMStatMfdCriteriaByUsingMchntNoAndDateRange(globalInstId, tmMcMchntInfo.getMchntNo(), DateUtil.getCurrentDate());
        } catch (Exception e) {
            rglog.error(e.getMessage());
        }
        /* 原手续费达标统计营销活动信息正式表查询 */
        McDetailInfoMapper mcDetailInfoMapper = new McDetailInfoMapperImpl();
        TMMcMchntFeeDiscountInfo tmMcMchntFeeDiscountInfo1 = null;
        if (null != tmStatMfdCriterias && !flow.equals(CommonConstant.ZERO_COMMON_CONSTANT)) {
            try {
                tmMcMchntFeeDiscountInfo1 = (TMMcMchntFeeDiscountInfo) mcDetailInfoMapper.selectMcDetailInfo(globalInstId, tmStatMfdCriterias.getMcNo(), TABLE_NAME);
            } catch (Exception e) {
                rglog.error(e.getMessage());
            }
            //如果达标统计表有当前交易日期商户达标的数据，则直接拒绝新增,原活动状态为自然结束，强制结束，已结束的数据作废
            if (null == tmMcMchntFeeDiscountInfo1 || !tmMcMchntFeeDiscountInfo1.getMcStatus().equals(McStatusEnum.ENDED.getMcStatusCode()) || !tmMcMchntFeeDiscountInfo1.getMcStatus().equals(McStatusEnum.FORCE_ENDED.getMcStatusCode()) || !tmMcMchntFeeDiscountInfo1.getMcStatus().equals(McStatusEnum.ALL_ENDED.getMcStatusCode())) {
                rglog.error("商户<{}>已参加其他手续费活动！", tmMcMchntInfo.getMchntNo());
                throw new BizException(RespCodeEnum.WRONG_MCHNT_ISALREADY_ORTHER_INMC_ERROR.getRespCode(), RespCodeEnum.WRONG_MCHNT_ISALREADY_ORTHER_INMC_ERROR.getRespDesc());
            }
        }
        TMStatMfdCriteria tmStatMfdCriteria = new TMStatMfdCriteria();
        //查询营销活动规则信息表
        McRuleInfoMapper mcRuleInfoMapper = new McRuleInfoMapperImpl();
        List<TMMcMchntFeeDiscountRuleInfo> tmMcMchntFeeDiscountRuleInfoList = new ArrayList<>();
        try {
            tmMcMchntFeeDiscountRuleInfoList = mcRuleInfoMapper.selectMchntFeeDiscountRuleInfoList(globalInstId, globalMcNo);
        } catch (Exception e) {
            rglog.error(e.getMessage());
        }
        //循环添加状态时 用到的
        List<TMMcMchntFeeDiscountRuleInfo> newtmMcMchntFeeDiscountRuleInfoList = tmMcMchntFeeDiscountRuleInfoList;
        if (null == tmMcMchntFeeDiscountRuleInfoList || tmMcMchntFeeDiscountRuleInfoList.size() == 0) {
            rglog.error("获取营销活动规则信息失败,营销活动号:<{}>", tmMcMchntInfo.getMcNo());
            throw new BizException(RespCodeEnum.GET_MC_RULE_INFO_ERROR.getRespCode(), RespCodeEnum.GET_MC_RULE_INFO_ERROR.getRespDesc());
        }
        try {
            /* 法人机构号 */
            tmStatMfdCriteria.setInstId(globalInstId);
            /* 营销活动编号 */
            tmStatMfdCriteria.setMcNo(tmMcMchntInfo.getMcNo());
            /* 营销商户编号 */
            tmStatMfdCriteria.setMchntNo(tmMcMchntInfo.getMchntNo());
            /* 统计起始日期 */
            String periodStartDate = MompDateUtil.getSecondDay(Integer.parseInt(globalTxnDate.substring(0, 4)), Integer.parseInt(globalTxnDate.substring(4, 6)));
            if (DateUtil.compareDate(periodStartDate, mcStartDate) < 0) {
                periodStartDate = mcStartDate;
            }
            tmStatMfdCriteria.setPeriodStartDate(periodStartDate);
            if (flow.equals(CommonConstant.ZERO_COMMON_CONSTANT)) {
                /* 统计起始日期 */
                tmStatMfdCriteria.setPeriodStartDate(DateUtil.getBaseDateOffsetDay(globalTxnDate, 1));
            }
            //如果是存量商户类型是商户上月日均存款
            if (tmMcMchntFeeDiscountInfo.getStockMchntType().equals(CommonConstant.OLD_MCHNT_DEPOSIT)) {
                //如果算出的结束日期大与活动结束日期，则保留活动结束日期
                if (DateUtil.compareTime(DateUtil.getBaseDateOffsetDay(MompDateUtil.getCurrentMonthLastDay(), 1), tmMcMchntFeeDiscountInfo.getMcEndDate(), "yyyyMMdd") > 0) {
                    /* 统计结束日期 */
                    tmStatMfdCriteria.setPeriodEndDate(tmMcMchntFeeDiscountInfo.getMcEndDate());
                } else {
                    /* 统计结束日期 -活动结束日期*/
                    tmStatMfdCriteria.setPeriodEndDate(DateUtil.getBaseDateOffsetDay(MompDateUtil.getCurrentMonthLastDay(), 1));
                }
            } else {
                if (tmMcMchntFeeDiscountRuleInfoList.get(0).getDiscountPeriod().equals(CommonConstant.MFD_PERIOD_MC)) {
                    /* 统计结束日期 */
                    tmStatMfdCriteria.setPeriodEndDate(mcEndDate);
                } else if (tmMcMchntFeeDiscountRuleInfoList.get(0).getDiscountPeriod().equals(CommonConstant.MFD_PERIOD_DAY)) {
                    /* 统计结束日期 */
                    tmStatMfdCriteria.setPeriodEndDate(globalTxnDate);
                } else if (tmMcMchntFeeDiscountRuleInfoList.get(0).getDiscountPeriod().equals(CommonConstant.MFD_PERIOD_MONTH)) {
                    //如果算出的结束日期大与活动结束日期，则保留活动结束日期
                    if (DateUtil.compareTime(DateUtil.getBaseDateOffsetDay(MompDateUtil.getCurrentMonthLastDay(), 1), tmMcMchntFeeDiscountInfo.getMcEndDate(), "yyyyMMdd") > 0) {
                        /* 统计结束日期 */
                        tmStatMfdCriteria.setPeriodEndDate(tmMcMchntFeeDiscountInfo.getMcEndDate());
                    } else {
                        /* 统计结束日期 -活动结束日期*/
                        tmStatMfdCriteria.setPeriodEndDate(DateUtil.getBaseDateOffsetDay(MompDateUtil.getCurrentMonthLastDay(), 1));
                    }
                } else if (tmMcMchntFeeDiscountRuleInfoList.get(0).getDiscountPeriod().equals(CommonConstant.MFD_PERIOD_QUARTER)) {
                    //如果算出的结束日期大与活动结束日期，则保留活动结束日期
                    if (DateUtil.compareTime(DateUtil.getBaseDateOffsetDay(MompDateUtil.quarterEnd(globalTxnDate), 1), tmMcMchntFeeDiscountInfo.getMcEndDate(), "yyyyMMdd") > 0) {
                        /* 统计结束日期 */
                        tmStatMfdCriteria.setPeriodEndDate(tmMcMchntFeeDiscountInfo.getMcEndDate());
                    } else {
                        /* 统计结束日期 */
                        tmStatMfdCriteria.setPeriodEndDate(DateUtil.getBaseDateOffsetDay(MompDateUtil.quarterEnd(globalTxnDate), 1));
                    }
                } else if (tmMcMchntFeeDiscountRuleInfoList.get(0).getDiscountPeriod().equals(CommonConstant.MFD_PERIOD_ANNUAL)) {
                    //如果算出的结束日期大与活动结束日期，则保留活动结束日期
                    if (DateUtil.compareTime(DateUtil.getBaseDateOffsetDay(MompDateUtil.getYearLastDay(), 1), tmMcMchntFeeDiscountInfo.getMcEndDate(), "yyyyMMdd") > 0) {
                        /* 统计结束日期 */
                        tmStatMfdCriteria.setPeriodEndDate(tmMcMchntFeeDiscountInfo.getMcEndDate());
                    } else {
                        /* 统计结束日期 */
                        tmStatMfdCriteria.setPeriodEndDate(DateUtil.getBaseDateOffsetDay(MompDateUtil.getYearLastDay(), 1));
                    }
                }
            }
            //存量商户类型
            tmStatMfdCriteria.setCriteriaType(tmMcMchntFeeDiscountInfo.getStockMchntType());
            /* 记录索引 */
            tmStatMfdCriteria.setRecIndex(CommonConstant.ACCT_FLAG_NORMAL);
            /* 达标前手续费优惠规则 */
            tmStatMfdCriteria.setBeforeFlag(beforeFlag);
            /* 达标后手续费优惠规则 */
            tmStatMfdCriteria.setAfterFlag(adterFlag);
            /* 商户新增标志 */
            tmStatMfdCriteria.setNewMchntFlag(CommonConstant.MCHNT_OLD_FLAG);
            /* 创建人 */
            tmStatMfdCriteria.setOprId(globalOprId);
            /* 创建时间 */
            tmStatMfdCriteria.setCreateTime(globalTimeStamp);
            /* 修改人 */
            tmStatMfdCriteria.setLastOprId(globalOprId);
            /* 修改时间 */
            tmStatMfdCriteria.setUpdateTime(globalTimeStamp);
            //存量商户当前统计值
            BigDecimal criteriaValue = new BigDecimal("0");
            //月平均存款总天数
            BigDecimal days = new BigDecimal("0");
            String month = MompDateUtil.getMonth();
            //如果存量商户支持类型是上月日均存款
            if (stockMchntType.equals(CommonConstant.OLD_MCHNT_DEPOSIT)) {
                TMMchntMonthDepositMapper tmMchntMonthDepositMapper = new TMMchntMonthDepositMapperImpl();
                for (int i = 1; i < Integer.parseInt(monthCount) + 1; i++) {
                    //获取指定月的上n个月
                    month = MompDateUtil.getLast12Month(i);
                    //上月天数
                    int monthDays = MompDateUtil.getMonthLastDay(Integer.parseInt(month.substring(0, 4)), Integer.parseInt(month.substring(4, 6)));
                    BigDecimal monthDayss = new BigDecimal(String.valueOf(monthDays));
                    //获取商户指定月份日均存款
                    TMMchntMonthDeposit tmMchntMonthDeposit = tmMchntMonthDepositMapper.selectLastMonthDepositInfo(globalInstId, tmMcMchntInfo.getMchntNo(), month);
                    if (null == tmMchntMonthDeposit) {
                        rglog.error("获取商户<{}>指定月<{}>日均存款失败,赋值为0", tmMcMchntInfo.getMchntNo(), month);
                        tmMchntMonthDeposit = new TMMchntMonthDeposit();
                        tmMchntMonthDeposit.setInstId(globalInstId);
                        tmMchntMonthDeposit.setMchntNo(tmMcMchntInfo.getMchntNo());
                        tmMchntMonthDeposit.setMchntMonth(month);
                        tmMchntMonthDeposit.setMchntDeposit(CommonConstant.ZERO_AMOUNT);
                    }
                    BigDecimal j = new BigDecimal(tmMchntMonthDeposit.getMchntDeposit()).setScale(CommonConstant.DECIMAL_SCALE_TWO, RoundingMode.HALF_UP);
                    criteriaValue = criteriaValue.add(monthDayss.multiply(j).setScale(CommonConstant.DECIMAL_SCALE_TWO, RoundingMode.HALF_UP));
                    days = days.add(monthDayss).setScale(CommonConstant.DECIMAL_SCALE_ZERO, RoundingMode.HALF_UP);
                }
                tmStatMfdCriteria.setCriteriaValue(String.valueOf(criteriaValue.divide(days, CommonConstant.DECIMAL_SCALE_TWO, RoundingMode.HALF_UP)));
                //现日均存款
                String dayMoney = String.valueOf(criteriaValue.divide(days, CommonConstant.DECIMAL_SCALE_TWO, RoundingMode.HALF_UP));
                //判断是否达标
                tmMcMchntFeeDiscountRuleInfoList = tmMcMchntFeeDiscountRuleInfoList.stream().filter(item -> String.valueOf(AmountUtil.compare(dayMoney, item.getCriteriaFloor())).equals(CommonConstant.STOCK_MCHNT_FLAG_ONE)).collect(Collectors.toList());
                if (tmMcMchntFeeDiscountRuleInfoList.size() > 0) {
                    //是否达标  已达标
                    tmStatMfdCriteria.setCriteriaFlag(CommonConstant.CRITERIA_FLAG_SET);
                    /* 优惠退出状态 */
                    tmStatMfdCriteria.setExitDiscountStatus(CommonConstant.MC_NOT_EXIT_FLAG);
                } else {
                    //是否达标 未达标
                    tmStatMfdCriteria.setCriteriaFlag(CommonConstant.CRITERIA_FLAG_NOT_SET);
                    /* 优惠退出状态 */
                    tmStatMfdCriteria.setExitDiscountStatus(CommonConstant.MC_EXIT_FLAG);
                }
            } else {
                tmStatMfdCriteria.setCriteriaValue(CommonConstant.ZERO_COMMON_CONSTANT);
                tmStatMfdCriteria.setCriteriaFlag(CommonConstant.CRITERIA_FLAG_NOT_SET);
                /* 优惠退出状态 */
                tmStatMfdCriteria.setExitDiscountStatus(CommonConstant.MC_EXIT_FLAG);

            }
            //插入营销活动商户统计表各规则当前周期为0的数据 活动转移商户不处理
            if (!flow.equals(CommonConstant.ZERO_COMMON_CONSTANT)) {
                addStatMfdMchnt(tmStatMfdCriteria, newtmMcMchntFeeDiscountRuleInfoList);
            }
            //循环添加手续费达标统计表
            if (DateUtil.compareTime(tmStatMfdCriteria.getPeriodEndDate(), tmMcMchntFeeDiscountInfo.getMcEndDate(), "yyyyMMdd") < 0) {
                addMfdCriteria(tmStatMfdCriteria, tmMcMchntFeeDiscountInfo, newtmMcMchntFeeDiscountRuleInfoList.get(0));
            }
        } catch (Exception e) {
            rglog.error("转换营销活动手续费达标统计信息异常,异常信息:<{}>", StringUtil.ExceptionToString(e));
            throw new BizException(e.getMessage());
        }

        return tmStatMfdCriteria;
    }

    /**
     * 循环添加手续费达标统计表
     *
     * @param tmStatMfdCriteria
     * @param tmMcMchntFeeDiscountInfo
     * @param tmMcMchntFeeDiscountRuleInfo
     * @throws Exception
     */
    private void addMfdCriteria(TMStatMfdCriteria tmStatMfdCriteria, TMMcMchntFeeDiscountInfo tmMcMchntFeeDiscountInfo, TMMcMchntFeeDiscountRuleInfo tmMcMchntFeeDiscountRuleInfo) throws Exception {
        List<TMStatMfdCriteria> tmStatMfdCriteriaLists = new ArrayList<>();
        //统计周期结束日期
        String month = DateUtil.getBaseDateOffsetDay(tmStatMfdCriteria.getPeriodEndDate(), 1);
        //记录引索
        int i = 2;
        rglog.info("手续费达标统计数据<{}>", tmStatMfdCriteria);
        rglog.info("活动信息表<{}>", tmMcMchntFeeDiscountInfo);
        rglog.info("规则信息表<{}>", tmMcMchntFeeDiscountRuleInfo);
        //循环生成手续费达标统计表数据，直至统计结束日期大于活动结束日期
        while (DateUtil.compareTime(DateUtil.getBaseDateOffsetDay(month, -1), tmMcMchntFeeDiscountInfo.getMcEndDate(), "yyyyMMdd") > 0) {
            TMStatMfdCriteria newtmStatMfdCriteria = new TMStatMfdCriteria();
            newtmStatMfdCriteria.setInstId(tmStatMfdCriteria.getInstId());
            newtmStatMfdCriteria.setMcNo(tmStatMfdCriteria.getMcNo());
            newtmStatMfdCriteria.setMchntNo(tmStatMfdCriteria.getMchntNo());
            /* 统计起始日期 */
            newtmStatMfdCriteria.setPeriodStartDate(month);
            /* 记录索引 */
            newtmStatMfdCriteria.setRecIndex(String.valueOf(i));
            rglog.info("记录索引<{}>", String.valueOf(i));
            //存量商户类型
            tmStatMfdCriteria.setCriteriaType(tmMcMchntFeeDiscountInfo.getStockMchntType());
            /* 达标前手续费优惠规则 */
            newtmStatMfdCriteria.setBeforeFlag(tmStatMfdCriteria.getBeforeFlag());
            /* 达标后手续费优惠规则 */
            newtmStatMfdCriteria.setAfterFlag(tmStatMfdCriteria.getAfterFlag());
            /* 商户新增标志 */
            newtmStatMfdCriteria.setNewMchntFlag(tmStatMfdCriteria.getNewMchntFlag());
            /* 优惠退出状态 */
            tmStatMfdCriteria.setExitDiscountStatus(CommonConstant.MC_EXIT_FLAG);
            /* 创建人 */
            newtmStatMfdCriteria.setOprId(globalOprId);
            /* 创建时间 */
            newtmStatMfdCriteria.setCreateTime(globalTimeStamp);
            /* 修改人 */
            newtmStatMfdCriteria.setLastOprId(globalOprId);
            /* 修改时间 */
            newtmStatMfdCriteria.setUpdateTime(globalTimeStamp);
            //存量商户当前统计值
            newtmStatMfdCriteria.setCriteriaValue(CommonConstant.ZERO_COMMON_CONSTANT);
            //存量商户达标标志
            newtmStatMfdCriteria.setCriteriaFlag(CommonConstant.CRITERIA_FLAG_NOT_SET);
            //如果是存量商户类型是商户上月日均存款
            if (tmMcMchntFeeDiscountInfo.getStockMchntType().equals(CommonConstant.OLD_MCHNT_DEPOSIT)) {
                //如果算出的结束日期大与活动结束日期，则保留活动结束日期
                if (DateUtil.compareTime(DateUtil.getBaseDateOffsetDay(MompDateUtil.getCurrentMonthLastDay(), 1), tmMcMchntFeeDiscountInfo.getMcEndDate(), "yyyyMMdd") > 0) {
                    /* 统计结束日期 */
                    newtmStatMfdCriteria.setPeriodEndDate(tmMcMchntFeeDiscountInfo.getMcEndDate());
                } else {
                    /* 统计结束日期 */
                    newtmStatMfdCriteria.setPeriodEndDate(DateUtil.getBaseDateOffsetDay(MompDateUtil.getCurrentMonthLastDay(), 1));
                }
                month = DateUtil.getBaseDateOffsetDay(MompDateUtil.getCurrentMonthLastDay(), 2);
            } else {//其他则按统计周期计算结束日期
                if (tmMcMchntFeeDiscountRuleInfo.getDiscountPeriod().equals(CommonConstant.MFD_PERIOD_MC)) {
                    /* 统计结束日期 */
                    newtmStatMfdCriteria.setPeriodEndDate(mcEndDate);
                } else if (tmMcMchntFeeDiscountRuleInfo.getDiscountPeriod().equals(CommonConstant.MFD_PERIOD_DAY)) {//与活动起止日期一致
                    /* 统计结束日期 */
                    newtmStatMfdCriteria.setPeriodEndDate(globalTxnDate);
                } else if (tmMcMchntFeeDiscountRuleInfo.getDiscountPeriod().equals(CommonConstant.MFD_PERIOD_MONTH)) {//自然月
                    //如果算出的结束日期大与活动结束日期，则保留活动结束日期
                    if (DateUtil.compareTime(DateUtil.getBaseDateOffsetDay(MompDateUtil.getCurrentMonthLastDay(), 1), tmMcMchntFeeDiscountInfo.getMcEndDate(), "yyyyMMdd") > 0) {
                        /* 统计结束日期 */
                        newtmStatMfdCriteria.setPeriodEndDate(tmMcMchntFeeDiscountInfo.getMcEndDate());
                    } else {
                        /* 统计结束日期 -活动结束日期*/
                        newtmStatMfdCriteria.setPeriodEndDate(DateUtil.getBaseDateOffsetDay(MompDateUtil.getCurrentMonthLastDay(), 1));
                    }
                    month = DateUtil.getBaseDateOffsetDay(MompDateUtil.getCurrentMonthLastDay(), 2);
                } else if (tmMcMchntFeeDiscountRuleInfo.getDiscountPeriod().equals(CommonConstant.MFD_PERIOD_QUARTER)) {//自然季度
                    //如果算出的结束日期大与活动结束日期，则保留活动结束日期
                    if (DateUtil.compareTime(DateUtil.getBaseDateOffsetDay(MompDateUtil.quarterEnd(globalTxnDate), 1), tmMcMchntFeeDiscountInfo.getMcEndDate(), "yyyyMMdd") > 0) {
                        /* 统计结束日期 */
                        newtmStatMfdCriteria.setPeriodEndDate(tmMcMchntFeeDiscountInfo.getMcEndDate());
                    } else {
                        /* 统计结束日期 */
                        newtmStatMfdCriteria.setPeriodEndDate(DateUtil.getBaseDateOffsetDay(MompDateUtil.quarterEnd(globalTxnDate), 1));
                    }
                    month = DateUtil.getBaseDateOffsetDay(MompDateUtil.quarterEnd(globalTxnDate), 2);
                } else if (tmMcMchntFeeDiscountRuleInfo.getDiscountPeriod().equals(CommonConstant.MFD_PERIOD_ANNUAL)) {//自然年
                    //如果算出的结束日期大与活动结束日期，则保留活动结束日期
                    if (DateUtil.compareTime(DateUtil.getBaseDateOffsetDay(MompDateUtil.getYearLastDay(), 1), tmMcMchntFeeDiscountInfo.getMcEndDate(), "yyyyMMdd") > 0) {
                        /* 统计结束日期 */
                        newtmStatMfdCriteria.setPeriodEndDate(tmMcMchntFeeDiscountInfo.getMcEndDate());
                    } else {
                        /* 统计结束日期 */
                        newtmStatMfdCriteria.setPeriodEndDate(DateUtil.getBaseDateOffsetDay(MompDateUtil.getYearLastDay(), 1));
                    }
                    month = DateUtil.getBaseDateOffsetDay(MompDateUtil.getYearLastDay(), 2);
                }
            }
            i++;
            rglog.info("生成的手续费达标统计数据<{}>", newtmStatMfdCriteria);
            tmStatMfdCriteriaLists.add(newtmStatMfdCriteria);
        }
        allSmStatMfdCriteriaList.addAll(tmStatMfdCriteriaLists);
    }

    /*
     *检查商户是否参加其他银行对商户手续费减免活动
     * @author JL Pang
     * @since 2020/9/10 22:26
     *tmMcMchntInfoList 新增商户list
     */
    private void checkMchntStatus(List<TMMcMchntInfo> newtmMcMchntInfoList, DbsUtil dbsUtil) throws Exception {
        //查询营销商户表数据
        McMchntInfoMapper mcMchntInfoMapper = new McMchntInfoMapperImpl();
        for (TMMcMchntInfo newtmMcMchntInfo : newtmMcMchntInfoList) {
            List<TMMcMchntInfo> tmMcMchntInfoList = mcMchntInfoMapper.selectMfdMchntInfoListByinstIdMchntNo(globalInstId, newtmMcMchntInfo.getMchntNo());
            if (null != tmMcMchntInfoList && tmMcMchntInfoList.size() > 0) {
                //去除本次活动和要转移的活动编号
                tmMcMchntInfoList = tmMcMchntInfoList.stream().filter(item -> !item.getMcNo().equals(globalMcNo) && !item.getMcNo().equals(relationMcNo)).collect(Collectors.toList());
                //上送商户是否参加了当前日期内其他进行中的手续费营销活动(new_mchnt_flag为1 exit_flag为1) (new_mchnt_flag为0 exit_flag为0)
                List<TMMcMchntInfo> jxzMchntList = tmMcMchntInfoList.stream().filter(item -> (item.getNewMchntFlag().equals(CommonConstant.MCHNT_OLD_FLAG) && item.getExitFlag().equals(CommonConstant.MC_NOT_EXIT_FLAG)) || (item.getNewMchntFlag().equals(CommonConstant.MCHNT_NEW_FLAG) && item.getExitFlag().equals(CommonConstant.MC_EXIT_FLAG))
                        || (item.getNewMchntFlag().equals(CommonConstant.MCHNT_OLD_FLAG) && item.getExitFlag().equals(CommonConstant.MC_EXIT_FLAG))).collect(Collectors.toList());
                rglog.info("营销活动商户信息表状态为(new_mchnt_flag为1 exit_flag为1)或(new_mchnt_flag为0 exit_flag为0)或(new_mchnt_flag为0 exit_flag为1)的条数<{}>", jxzMchntList.size());
                if (jxzMchntList.size() > 0) {
                    for (TMMcMchntInfo tmMcMchntInfo : jxzMchntList) {
                        /* 营销活动信息正式表查询 */
                        McDetailInfoMapper mcDetailInfoMapper = new McDetailInfoMapperImpl();
                        TMMcMchntFeeDiscountInfo tmMcMchntFeeDiscountInfo = (TMMcMchntFeeDiscountInfo) mcDetailInfoMapper.selectMcDetailInfo(globalInstId, tmMcMchntInfo.getMcNo(), TableNameEnum.T_M_MC_MFD_INFO.getTableNameCode());
                        //如果活动状态不是自然结束，强制结束，草稿；审批状态不是新增拒绝，审批拒绝，发布拒绝的状态，直接抛异常
                        if (null != tmMcMchntFeeDiscountInfo && !tmMcMchntFeeDiscountInfo.getMcStatus().equals(McStatusEnum.ENDED.getMcStatusCode()) && !tmMcMchntFeeDiscountInfo.getMcStatus().equals(McStatusEnum.FORCE_ENDED.getMcStatusCode()) && !tmMcMchntFeeDiscountInfo.getMcStatus().equals(McStatusEnum.ALL_ENDED.getMcStatusCode())
                                && !tmMcMchntFeeDiscountInfo.getAuditStatus().equals(AuditStatusEnum.NEW_AUDIT_REJECT.getAuditStatusCode()) && !tmMcMchntFeeDiscountInfo.getAuditStatus().equals(AuditStatusEnum.MODIFY_AUDIT_REJECT.getAuditStatusCode()) && !tmMcMchntFeeDiscountInfo.getAuditStatus().equals(AuditStatusEnum.PUBLISH_AUDIT_REJECT.getAuditStatusCode())
                                && !tmMcMchntFeeDiscountInfo.getMcStatus().equals(McStatusEnum.DRAFT.getMcStatusCode())) {
                            rglog.error("商户<{}>已参加其他进行中手续费活动<{}>！", tmMcMchntInfo.getMchntNo(), tmMcMchntFeeDiscountInfo.getMcNo());
                            dbsUtil.dbsEndTransaction(false);
                            throw new BizException(RespCodeEnum.WRONG_MCHNT_ISALREADY_INMC_ERROR.getRespCode(), RespCodeEnum.WRONG_MCHNT_ISALREADY_INMC_ERROR.getRespDesc() + ",商户<" + tmMcMchntInfo.getMchntNo() + ">");
                        }
                    }
                }
                //上送商户是否有从a活动到b活动的转移(new_mchnt_flag为2 exit_flag为2) (new_mchnt_flag为1 exit_flag为2)
                List<TMMcMchntInfo> zyMchntList = tmMcMchntInfoList.stream().filter(item -> (item.getNewMchntFlag().equals(CommonConstant.MCHNT_REFUSE_FLAG) && item.getExitFlag().equals(CommonConstant.MC_TRANSFER_FLAG)) || (item.getNewMchntFlag().equals(CommonConstant.MCHNT_NEW_FLAG) && item.getExitFlag().equals(CommonConstant.MC_TRANSFER_FLAG))).collect(Collectors.toList());
                rglog.info("营销活动商户信息表状态为(new_mchnt_flag为2 exit_flag为2)或(new_mchnt_flag为1 exit_flag为2)的条数<{}>", zyMchntList.size());
                if (zyMchntList.size() > 0) {
                    for (TMMcMchntInfo tmMcMchntInfo : zyMchntList) {
                        /* 营销活动信息正式表查询 */
                        McDetailInfoMapper mcDetailInfoMapper = new McDetailInfoMapperImpl();
                        TMMcMchntFeeDiscountInfo tmMcMchntFeeDiscountInfo = (TMMcMchntFeeDiscountInfo) mcDetailInfoMapper.selectMcDetailInfo(globalInstId, tmMcMchntInfo.getMcNo(), TableNameEnum.T_M_MC_MFD_INFO.getTableNameCode());
                        if (null != tmMcMchntFeeDiscountInfo && !tmMcMchntFeeDiscountInfo.getMcStatus().equals(McStatusEnum.ENDED.getMcStatusCode()) && !tmMcMchntFeeDiscountInfo.getMcStatus().equals(McStatusEnum.FORCE_ENDED.getMcStatusCode()) && !tmMcMchntFeeDiscountInfo.getMcStatus().equals(McStatusEnum.ALL_ENDED.getMcStatusCode())) {
                            rglog.error("商户<{}>正在进行活动转移！", tmMcMchntInfo.getMchntNo(), tmMcMchntFeeDiscountInfo.getMcNo());
                            dbsUtil.dbsEndTransaction(false);
                            throw new BizException(RespCodeEnum.MCHNT_TRANSFER_WRONG.getRespCode(), RespCodeEnum.MCHNT_TRANSFER_WRONG.getRespDesc() + ",商户<" + tmMcMchntInfo.getMchntNo() + ">");
                        }
                    }
                }
            }
        }
    }

    /**
     * 处理新旧营销活动统计表数据
     *
     * @param dbsUtil
     * @throws Exception
     */
    private void chulitjb(DbsUtil dbsUtil) throws Exception {
        //手续费营销活动商户统计表
        TMStatMfdMchntMapper tmStatMfdMchntMapper = new TMStatMfdMchntMapperImpl();
        //手续费达标统计表
        TMStatMfdCriteriaMapper tmStatMfdCriteriaMapper = new TMStatMfdCriteriaMapperImpl();
        //商户正式表
        McMchntInfoMapper mcMchntInfoMapper = new McMchntInfoMapperImpl();
        //临时表
        PlatBizTmpMapper platBizTmpMapper = new PlatBizTmpMapperImpl();
        int returnCode = 0;
        //要删除的临时表商户信息
        List<TMPlatBizTmp> tmPlatBizTmpList1 = new ArrayList<>();
        List<TMMcMchntInfo> tmMcMchntInfoList = mcMchntInfoMapper.selectMchntByinstIdNewMcNo(globalInstId, globalMcNo);
        if (null != tmMcMchntInfoList && tmMcMchntInfoList.size() > 0) {
            for (TMMcMchntInfo tmMcMchntInfo : tmMcMchntInfoList) {
                rglog.info("查询旧手续费营销活动商户统计表，商户号<{}>,营销活动编号<{}>", tmMcMchntInfo.getMchntNo(), tmMcMchntInfo.getMcNo());
                List<TMStatMfdMchnt> oldtmStatMfdMchntList = tmStatMfdMchntMapper.selectMFDiscountMchntStatisticsByinstIdMcNoMchntNo(globalInstId, tmMcMchntInfo.getMcNo(), tmMcMchntInfo.getMchntNo(), globalTxnDate);
                if (null != oldtmStatMfdMchntList && oldtmStatMfdMchntList.size() > 0) {
                    rglog.info("查询到旧手续费营销活动商户统计表数据<{}>条", oldtmStatMfdMchntList.size());
                    rglog.info("开始更新旧手续费营销活动商户统计表数据");
                    for (TMStatMfdMchnt tmStatMfdMchnt : oldtmStatMfdMchntList) {
                        rglog.info("商户统计表营销活动编号<{}>,商户号<{}>,顺序号<{}>", tmStatMfdMchnt.getMcNo(), tmStatMfdMchnt.getMchntNo(), tmStatMfdMchnt.getRuleIndex());
                        tmStatMfdMchnt.setStatEndDate(globalTxnDate);
                        //更新手续费营销活动商户统计表数据
                        returnCode = tmStatMfdMchntMapper.updateMfdEndDate(tmStatMfdMchnt);
                        if (cc.rengu.utility.dbs.Database.DBS_SUCCESS != returnCode) {
                            /* 营销活动临时数据审批状态异常，不可审批通过 */
                            dbsUtil.dbsEndTransaction(false);
                            rglog.error("{}, RETURN_CODE=<{}>, MC_NO=<{}>", RespCodeEnum.DATABASE_OPR_ERROR.getRespDesc(), returnCode, tmMcMchntInfo.getMcNo());
                            throw new BizException(RespCodeEnum.DATABASE_OPR_ERROR.getRespCode(), RespCodeEnum.DATABASE_OPR_ERROR.getRespDesc());
                        }
                    }
                } else {
                    rglog.info("未查询到旧手续费营销活动商户统计表数据");
                }
                rglog.info("开始查询旧营销活动手续费达标统计表数据");
                TMStatMfdCriteria tmStatMfdCriteria = tmStatMfdCriteriaMapper.selectTMStatMfdCriteriaByUsingMchntNoAndMcNoAndDateRange(globalInstId, tmMcMchntInfo.getMchntNo(), globalTxnDate, tmMcMchntInfo.getMcNo());
                if (null != tmStatMfdCriteria) {
                    rglog.info("修改营销活动<{}>下商户<{}>的手续费达标统计表统计结束日期", tmMcMchntInfo.getMcNo(), tmMcMchntInfo.getMchntNo());
                    tmStatMfdCriteria.setRemark1(globalTxnDate);
                    returnCode = tmStatMfdCriteriaMapper.updateTMstatMfdCriteriaEndDateByPrimaryKey(tmStatMfdCriteria);
                    if (cc.rengu.utility.dbs.Database.DBS_SUCCESS != returnCode) {
                        dbsUtil.dbsEndTransaction(false);
                        rglog.error("{}, RETURN_CODE=<{}>, MC_NO=<{}>", RespCodeEnum.DATABASE_OPR_ERROR.getRespDesc(), returnCode, tmMcMchntInfo.getMcNo());
                        throw new BizException(RespCodeEnum.DATABASE_OPR_ERROR.getRespCode(), RespCodeEnum.DATABASE_OPR_ERROR.getRespDesc());
                    }
                    //查询统计开始日期大于等于今天的旧营销活动商户手续达标统计数据
                    List<TMStatMfdCriteria> tmStatMfdCriteriaList = tmStatMfdCriteriaMapper.selectCriteriaInfoListByinstIdMchntNoMcNoDate(tmMcMchntInfo.getInstId(), tmMcMchntInfo.getMchntNo(), tmMcMchntInfo.getMcNo(), globalTxnDate);
                    if (null != tmStatMfdCriteriaList && tmStatMfdCriteriaList.size() > 0) {
                        //删除统计开始日期大于等于今天的旧营销活动商户手续达标统计数据
                        returnCode = tmStatMfdCriteriaMapper.deletetmStatMfdCriteria(tmStatMfdCriteriaList);
                        if (cc.rengu.utility.dbs.Database.DBS_SUCCESS != returnCode) {
                            dbsUtil.dbsEndTransaction(false);
                            rglog.error("{}, RETURN_CODE=<{}>, MC_NO=<{}>", RespCodeEnum.DATABASE_OPR_ERROR.getRespDesc(), returnCode, tmMcMchntInfo.getMcNo());
                            throw new BizException(RespCodeEnum.DATABASE_OPR_ERROR.getRespCode(), RespCodeEnum.DATABASE_OPR_ERROR.getRespDesc());
                        }
                    }
                } else {
                    rglog.info("未查询到旧营销活动手续费达标统计表数据");
                }
                //删除旧活动正式商户表信息
                returnCode = mcMchntInfoMapper.deleteMchntInfo(globalInstId, tmMcMchntInfo.getMcNo(), tmMcMchntInfo.getMchntNo());
                if (cc.rengu.utility.dbs.Database.DBS_SUCCESS != returnCode) {
                    dbsUtil.dbsEndTransaction(false);
                    rglog.error("{}, RETURN_CODE=<{}>, MC_NO=<{}>,MCHNT_NO=<{}>", RespCodeEnum.DELETE_MC_MCHNT_DATA_ERROR.getRespDesc(), returnCode, tmMcMchntInfo.getMcNo(), tmMcMchntInfo.getMchntNo());
                    throw new BizException(RespCodeEnum.DELETE_MC_MCHNT_DATA_ERROR.getRespCode(), RespCodeEnum.DELETE_MC_MCHNT_DATA_ERROR.getRespDesc());
                }
                rglog.info("更新新营销活动正式表信息");
                //更新新营销活动正式表信息
                TMMcMchntInfo newTmmchntInfo = new TMMcMchntInfo();
                newTmmchntInfo.setInstId(globalInstId);
                newTmmchntInfo.setMcNo(globalMcNo);
                newTmmchntInfo.setUpdateTime(globalTimeStamp);
                newTmmchntInfo.setExitFlag(CommonConstant.MC_NOT_EXIT_FLAG);
                newTmmchntInfo.setNewMchntFlag(CommonConstant.MCHNT_OLD_FLAG);
                returnCode = mcMchntInfoMapper.updateExitFlagAndNewMchntFlag(newTmmchntInfo);
                if (cc.rengu.utility.dbs.Database.DBS_SUCCESS != returnCode) {
                    dbsUtil.dbsEndTransaction(false);
                    rglog.error("{}, RETURN_CODE=<{}>, MC_NO=<{}>,MCHNT_NO=<{}>", RespCodeEnum.WRONG_UPDATEMCMCHNT_ERROR.getRespDesc(), returnCode);
                    throw new BizException(RespCodeEnum.WRONG_UPDATEMCMCHNT_ERROR.getRespCode(), RespCodeEnum.WRONG_UPDATEMCMCHNT_ERROR.getRespDesc());
                }
                //要删除旧营销活动的临时表数据
                TMPlatBizTmp tmPlatBizTmp = new TMPlatBizTmp();
                tmPlatBizTmp.setMcNo(tmMcMchntInfo.getMcNo());
                tmPlatBizTmp.setInstId(tmMcMchntInfo.getInstId());
                tmPlatBizTmp.setMchntNo(tmMcMchntInfo.getMchntNo());
                tmPlatBizTmpList1.add(tmPlatBizTmp);
            }
            //删除旧营销活动临时表商户信息
            returnCode = platBizTmpMapper.deleteByMcNoMchntNoTablename(tmPlatBizTmpList1);
            if (cc.rengu.utility.dbs.Database.DBS_SUCCESS != returnCode) {
                dbsUtil.dbsEndTransaction(false);
                rglog.error("{}, RETURN_CODE=<{}>, MC_NO=<{}>,MCHNT_NO=<{}>", RespCodeEnum.DELETE_MC_MCHNT_DATA_ERROR.getRespDesc(), returnCode);
                throw new BizException(RespCodeEnum.DELETE_MC_MCHNT_DATA_ERROR.getRespCode(), RespCodeEnum.DELETE_MC_MCHNT_DATA_ERROR.getRespDesc());
            }
        }
    }

    /**
     * 插入营销活动商户统计表
     *
     * @param tmStatMfdCriteria                第一个周期商户达标统计表数据
     * @param tmMcMchntFeeDiscountRuleInfoList 活动规则信息
     * @throws Exception
     * @author JL PANG
     */
    private void addStatMfdMchnt(TMStatMfdCriteria tmStatMfdCriteria, List<TMMcMchntFeeDiscountRuleInfo> tmMcMchntFeeDiscountRuleInfoList) throws Exception {
        for (TMMcMchntFeeDiscountRuleInfo tmMcMchntFeeDiscountRuleInfo : tmMcMchntFeeDiscountRuleInfoList) {
            TMStatMfdMchnt tmStatMfdMchnt = new TMStatMfdMchnt();
            //法人机构号
            tmStatMfdMchnt.setInstId(tmStatMfdCriteria.getInstId());
            //营销活动编号
            tmStatMfdMchnt.setMcNo(tmStatMfdCriteria.getMcNo());
            //商户号
            tmStatMfdMchnt.setMchntNo(tmStatMfdCriteria.getMchntNo());
            //统计开始日期
            tmStatMfdMchnt.setStatStartDate(tmStatMfdCriteria.getPeriodStartDate());
            //统计结束日期
            tmStatMfdMchnt.setStatEndDate(tmStatMfdCriteria.getPeriodEndDate());
            //规则号
            tmStatMfdMchnt.setRuleIndex(tmMcMchntFeeDiscountRuleInfo.getRuleIndex());
            //累计优惠金额
            tmStatMfdMchnt.setTotalAmtAcc(CommonConstant.ZERO_AMOUNT);
            //累计优惠笔数
            tmStatMfdMchnt.setTotalQtyAcc(CommonConstant.ZERO_COMMON_CONSTANT);
            //累计打款金额
            tmStatMfdMchnt.setCashbackAmtAcc(CommonConstant.ZERO_AMOUNT);
            //累计交易金额
            tmStatMfdMchnt.setTxnAmtAcc(CommonConstant.ZERO_AMOUNT);
            //累计交易笔数
            tmStatMfdMchnt.setTxnQtyAcc(CommonConstant.ZERO_COMMON_CONSTANT);
            //日均优惠金额
            tmStatMfdMchnt.setDayAvgAmt(CommonConstant.ZERO_AMOUNT);
            //笔均优惠金额
            tmStatMfdMchnt.setTotalAvgAmt(CommonConstant.ZERO_AMOUNT);
            //优惠退出状态
            tmStatMfdMchnt.setExitStatus(CommonConstant.MC_NOT_EXIT_FLAG);
            //创建人
            tmStatMfdMchnt.setOprId(tmStatMfdCriteria.getOprId());
            //创建时间
            tmStatMfdMchnt.setCreateTime(tmStatMfdCriteria.getCreateTime());
            //修改人
            tmStatMfdMchnt.setLastOprId(tmStatMfdCriteria.getOprId());
            //修改时间
            tmStatMfdMchnt.setUpdateTime(tmStatMfdCriteria.getCreateTime());
            tmStatMfdMchntList.add(tmStatMfdMchnt);
        }
    }

    /**
     * 强制结束进行中营销活动
     *
     * @param xmlTreeUtil 内部XML树
     * @throws Exception 异常信息
     * @author JL Pang
     * @date 2021/1/25 01:37
     */
    private void forceStopMc(XmlTreeUtil xmlTreeUtil) throws Exception {

        int returnCode;

        /* 开启数据库事务 */
        String dbPoolName = XmlConfigUtil.getXmlConfigCacheKeyValue(AppConfigConstant.DATABASE_CONF_NODE, AppConfigConstant.MOMP_POOL_NAME);
        String corporation = xmlTreeUtil.getXmlTreeStringValue(AppParamConstant.CORPORATION);
        if (null != corporation && !corporation.isEmpty()) {
            String dbPoolCashNode = corporation.trim() + AppParamConstant.DATABASE_CONF_NODE;
            dbPoolName = XmlConfigUtil.getXmlConfigCacheKeyValue(dbPoolCashNode, AppConfigConstant.MOMP_POOL_NAME);
        }
        DbsUtil dbsUtil = new DbsUtil(dbPoolName);
        dbsUtil.dbsBeginTransaction();

        /* 检查手续费减免类营销活动信息表的正式表中的营销活动状态 */
        if (McStatusEnum.PROGRESSING.getMcStatusCode().equals(this.tmMcMchntFeeDiscountInfo.getMcStatus()) || McStatusEnum.PAUSED.getMcStatusCode().equals(this.tmMcMchntFeeDiscountInfo.getMcStatus())) {

            /* 更新正式表数据状态 */
            TMMcMchntFeeDiscountInfo tmMcMchntFeeDiscountInfo = new TMMcMchntFeeDiscountInfo();
            tmMcMchntFeeDiscountInfo.setInstId(globalInstId);
            tmMcMchntFeeDiscountInfo.setMcNo(globalMcNo);
            tmMcMchntFeeDiscountInfo.setMcStatus(McStatusEnum.FORCE_ENDED.getMcStatusCode());
            tmMcMchntFeeDiscountInfo.setLastOprId(globalOprId);
            tmMcMchntFeeDiscountInfo.setUpdateTime(globalTimeStamp);
            tmMcMchntFeeDiscountInfo.setMcEndDate(DateUtil.getCurrentDate());
            tmMcMchntFeeDiscountInfo.setNfrcTmnlRsn(oprContent);

            returnCode = updatePausedMcMcStatusForEnabling(tmMcMchntFeeDiscountInfo);
            if (Database.DBS_SUCCESS != returnCode) {
                rglog.error("强制结束进行中商户手续费优惠类营销活动信息更新正式表数据失败！RETURN_CODE=<{}>", returnCode);
                dbsUtil.dbsEndTransaction(false);
                throw new BizException(RespCodeEnum.SYSTEM_ERROR.getRespCode(), RespCodeEnum.SYSTEM_ERROR.getRespDesc());
            }
            //查询临时表状态
            checkTmPStatus(globalInstId, globalMcNo);
            /* 更新临时表数据状态 */
            TMPlatBizTmp tmPlatBizTmp = new TMPlatBizTmp();
            tmPlatBizTmp.setInstId(globalInstId);
            tmPlatBizTmp.setMcNo(globalMcNo);
            tmPlatBizTmp.setBizOpr(BizOprEnum.SUSPEND.getBizOprCode());
            tmPlatBizTmp.setBizStatus(bizStatus);
            tmPlatBizTmp.setMcStatus(McStatusEnum.FORCE_ENDED.getMcStatusCode());
            tmPlatBizTmp.setAuditStatus(auditStatus);
            tmPlatBizTmp.setLastOprId(globalOprId);
            tmPlatBizTmp.setLastUpdateTime(globalTimeStamp);

            returnCode = updatePausedMcForEnabling(tmPlatBizTmp);
            if (Database.DBS_SUCCESS != returnCode) {
                rglog.error("强制结束进行中商户手续费优惠类营销活动信息更新临时表数据失败！RETURN_CODE=<{}>", returnCode);
                dbsUtil.dbsEndTransaction(false);
                throw new BizException(RespCodeEnum.SYSTEM_ERROR.getRespCode(), RespCodeEnum.SYSTEM_ERROR.getRespDesc());
            }
            //将周期开始时间大于终止时间的手续达标统计表数据优惠状态修改为已退出状态
            TMStatMfdCriteriaMapper tmStatMfdCriteriaMapper = new TMStatMfdCriteriaMapperImpl();
            TMStatMfdCriteria tmStatMfdCriteriaCount = tmStatMfdCriteriaMapper.selectCriteriaInfoListCountByinstIdMcNoDate(globalInstId, globalMcNo, globalTxnDate);
            TMStatMfdCriteria presentTmStatMfdCriteriaCount = tmStatMfdCriteriaMapper.selectTMStatMfdCriteriaCountByMcNoAndDateRange(globalInstId, globalMcNo, globalTxnDate);

            if (Integer.valueOf(tmStatMfdCriteriaCount.getRemark5()) + Integer.valueOf(presentTmStatMfdCriteriaCount.getRemark5()) > 0) {
                TMStatMfdCriteria tmStatMfdCriteria = new TMStatMfdCriteria();
                tmStatMfdCriteria.setInstId(globalInstId);
                tmStatMfdCriteria.setMcNo(globalMcNo);
                tmStatMfdCriteria.setExitDiscountStatus(CommonConstant.MC_EXIT_FLAG);
                returnCode = tmStatMfdCriteriaMapper.updateTMstatMfdCriteriaExitDiscountStatusByPrimaryKey(tmStatMfdCriteria);
                if (Database.DBS_SUCCESS != returnCode) {
                    rglog.error("强制结束进行中商户手续费优惠类营销活动信息更新手续费达标统计表数据失败！RETURN_CODE=<{}>", returnCode);
                    dbsUtil.dbsEndTransaction(false);
                    throw new BizException(RespCodeEnum.SYSTEM_ERROR.getRespCode(), RespCodeEnum.SYSTEM_ERROR.getRespDesc());
                }
            }

        } else {
            rglog.error("营销活动状态异常，不可强制结束进行中的商户手续费优惠类营销活动！MC_STATUS=<{}>", this.tmMcMchntFeeDiscountInfo.getMcStatus());
            dbsUtil.dbsEndTransaction(false);
            throw new BizException(RespCodeEnum.SYSTEM_ERROR.getRespCode(), RespCodeEnum.SYSTEM_ERROR.getRespDesc());
        }

        dbsUtil.dbsEndTransaction(true);
    }

    /**
     * @param instId 法人机构号
     * @param mcNo   营销活动编号
     * @throws Exception
     * @author JL Pang
     * @date 2021/1/25 01:37
     * 查询营销活动临时表活动信息
     */
    private void checkTmPStatus(String instId, String mcNo) throws Exception {
        PlatBizTmpMapper platBizTmpMapper = new PlatBizTmpMapperImpl();
        TMPlatBizTmp tmPlatBizTmp = platBizTmpMapper.selectTmpMcInfo(instId, mcNo, TABLE_NAME);
        if (null != tmPlatBizTmp) {
            auditStatus = tmPlatBizTmp.getAuditStatus();
            bizStatus = tmPlatBizTmp.getBizStatus();
        }
    }

    /**
     * 启用已暂停营销活动更新临时表数据
     *
     * @param tmPlatBizTmp 业务数据临时表
     * @return int 返回码
     * @throws Exception 异常信息
     */
    private int updatePausedMcForEnabling(TMPlatBizTmp tmPlatBizTmp) throws Exception {

        PlatBizTmpMapper platBizTmpMapper = new PlatBizTmpMapperImpl();
        return platBizTmpMapper.updatePausedMcForEnabling(tmPlatBizTmp);
    }

    /**
     * 启用已暂停营销活动更新正式表数据
     *
     * @param tmMcMchntFeeDiscountInfo 手续费营销活动信息表
     * @return int 返回码
     * @throws Exception 异常信息
     * @author JL Pang
     * @date 2021/2/3 17:46
     */
    private int updatePausedMcMcStatusForEnabling(TMMcMchntFeeDiscountInfo tmMcMchntFeeDiscountInfo) throws Exception {

        McDetailInfoMapper mcDetailInfoMapper = new McDetailInfoMapperImpl();
        return mcDetailInfoMapper.updatePausedMcMcStatusForEnabling(tmMcMchntFeeDiscountInfo, TABLE_NAME);
    }

    /**
     * 启用已暂停营销活动
     *
     * @param xmlTreeUtil 内部XML树
     * @throws Exception 异常信息
     * @author JL Pang
     * @date 2021/2/3 17:46
     */
    private void enableMc(XmlTreeUtil xmlTreeUtil) throws Exception {

        int returnCode;

        /* 开启数据库事务 */
        String dbPoolName = XmlConfigUtil.getXmlConfigCacheKeyValue(AppConfigConstant.DATABASE_CONF_NODE, AppConfigConstant.MOMP_POOL_NAME);
        String corporation = xmlTreeUtil.getXmlTreeStringValue(AppParamConstant.CORPORATION);
        if (null != corporation && !corporation.isEmpty()) {
            String dbPoolCashNode = corporation.trim() + AppParamConstant.DATABASE_CONF_NODE;
            dbPoolName = XmlConfigUtil.getXmlConfigCacheKeyValue(dbPoolCashNode, AppConfigConstant.MOMP_POOL_NAME);
        }
        DbsUtil dbsUtil = new DbsUtil(dbPoolName);
        dbsUtil.dbsBeginTransaction();

        //检查代理商分润类营销活动信息表的正式表中的营销活动状态
        if (McStatusEnum.PAUSED.getMcStatusCode().equals(tmMcMchntFeeDiscountInfo.getMcStatus())) {
            //更新正式表数据状态
            TMMcMchntFeeDiscountInfo tmMcMchntFeeDiscountInfo = new TMMcMchntFeeDiscountInfo();
            tmMcMchntFeeDiscountInfo.setInstId(globalInstId);
            tmMcMchntFeeDiscountInfo.setMcNo(globalMcNo);
            tmMcMchntFeeDiscountInfo.setMcStatus(McStatusEnum.PROGRESSING.getMcStatusCode());
            tmMcMchntFeeDiscountInfo.setLastOprId(globalOprId);
            tmMcMchntFeeDiscountInfo.setUpdateTime(globalTimeStamp);
            tmMcMchntFeeDiscountInfo.setMcEndDate(mcEndDate);

            returnCode = updatePausedMcMcStatusForEnabling(tmMcMchntFeeDiscountInfo);
            if (Database.DBS_SUCCESS != returnCode) {
                rglog.error("启用已暂停银行对商户手续费优惠营销活动信息正式表失败！RETURN_CODE=<{}>", returnCode);
                dbsUtil.dbsEndTransaction(false);
                throw new BizException(RespCodeEnum.SYSTEM_ERROR.getRespCode(), RespCodeEnum.SYSTEM_ERROR.getRespDesc());
            }

            //更新临时表数据状态 */
            //查询临时表状态
            checkTmPStatus(globalInstId, globalMcNo);
            TMPlatBizTmp tmPlatBizTmp = new TMPlatBizTmp();
            tmPlatBizTmp.setInstId(globalInstId);
            tmPlatBizTmp.setMcNo(globalMcNo);
            tmPlatBizTmp.setBizOpr(BizOprEnum.ENABLE.getBizOprCode());
            tmPlatBizTmp.setBizStatus(bizStatus);
            tmPlatBizTmp.setMcStatus(McStatusEnum.PROGRESSING.getMcStatusCode());
            tmPlatBizTmp.setAuditStatus(AuditStatusEnum.PUBLISH_AUDIT_PASSED.getAuditStatusCode());
            tmPlatBizTmp.setLastOprId(globalOprId);
            tmPlatBizTmp.setLastUpdateTime(globalTimeStamp);

            returnCode = updatePausedMcForEnabling(tmPlatBizTmp);
            if (Database.DBS_SUCCESS != returnCode) {
                rglog.error("启用已暂停银行对商户手续费营销活动信息临时表失败！RETURN_CODE=<{}>", returnCode);
                dbsUtil.dbsEndTransaction(false);
                throw new BizException(RespCodeEnum.SYSTEM_ERROR.getRespCode(), RespCodeEnum.SYSTEM_ERROR.getRespDesc());
            }

        } else {
            rglog.error("营销活动状态异常，不可启用营销活动！MC_STATUS=<{}>", tmMcMchntFeeDiscountInfo.getMcStatus());
            dbsUtil.dbsEndTransaction(false);
            throw new BizException(RespCodeEnum.SYSTEM_ERROR.getRespCode(), RespCodeEnum.SYSTEM_ERROR.getRespDesc());
        }

        dbsUtil.dbsEndTransaction(true);
    }

    /**
     * 暂停进行中营销活动
     *
     * @param xmlTreeUtil 内部XML树
     * @throws Exception 异常信息
     * @author JL Pang
     * @date 2021/2/3 17:46
     */
    private void pauseMc(XmlTreeUtil xmlTreeUtil) throws Exception {

        int returnCode;

        /* 开启数据库事务 */
        String dbPoolName = XmlConfigUtil.getXmlConfigCacheKeyValue(AppConfigConstant.DATABASE_CONF_NODE, AppConfigConstant.MOMP_POOL_NAME);
        String corporation = xmlTreeUtil.getXmlTreeStringValue(AppParamConstant.CORPORATION);
        if (null != corporation && !corporation.isEmpty()) {
            String dbPoolCashNode = corporation.trim() + AppParamConstant.DATABASE_CONF_NODE;
            dbPoolName = XmlConfigUtil.getXmlConfigCacheKeyValue(dbPoolCashNode, AppConfigConstant.MOMP_POOL_NAME);
        }
        DbsUtil dbsUtil = new DbsUtil(dbPoolName);
        dbsUtil.dbsBeginTransaction();

        /* 检查代理商分润类营销活动信息表的正式表中的营销活动状态 */
        if (McStatusEnum.PROGRESSING.getMcStatusCode().equals(tmMcMchntFeeDiscountInfo.getMcStatus())) {

            //更新正式表数据状态
            TMMcMchntFeeDiscountInfo tmMcMchntFeeDiscountInfo = new TMMcMchntFeeDiscountInfo();
            tmMcMchntFeeDiscountInfo.setInstId(globalInstId);
            tmMcMchntFeeDiscountInfo.setMcNo(globalMcNo);
            tmMcMchntFeeDiscountInfo.setMcStatus(McStatusEnum.PAUSED.getMcStatusCode());
            tmMcMchntFeeDiscountInfo.setLastOprId(globalOprId);
            tmMcMchntFeeDiscountInfo.setUpdateTime(globalTimeStamp);
            tmMcMchntFeeDiscountInfo.setMcEndDate(mcEndDate);

            returnCode = updatePausedMcMcStatusForEnabling(tmMcMchntFeeDiscountInfo);
            if (Database.DBS_SUCCESS != returnCode) {
                rglog.error("暂停进行中银行对商户手续费优惠营销活动信息更新正式表数据失败！RETURN_CODE=<{}>", returnCode);
                dbsUtil.dbsEndTransaction(false);
                throw new BizException(RespCodeEnum.SYSTEM_ERROR.getRespCode(), RespCodeEnum.SYSTEM_ERROR.getRespDesc());
            }
            //查询临时表状态
            checkTmPStatus(globalInstId, globalMcNo);
            //更新临时表数据状态
            TMPlatBizTmp tmPlatBizTmp = new TMPlatBizTmp();
            tmPlatBizTmp.setInstId(globalInstId);
            tmPlatBizTmp.setMcNo(globalMcNo);
            tmPlatBizTmp.setBizOpr(BizOprEnum.SUSPEND.getBizOprCode());
            tmPlatBizTmp.setBizStatus(BizStatusEnum.NORMAL_STATUS.getBizStatusCode());
            tmPlatBizTmp.setMcStatus(McStatusEnum.PAUSED.getMcStatusCode());
            tmPlatBizTmp.setAuditStatus(AuditStatusEnum.PUBLISH_AUDIT_PASSED.getAuditStatusCode());
            tmPlatBizTmp.setLastOprId(globalOprId);
            tmPlatBizTmp.setLastUpdateTime(globalTimeStamp);

            returnCode = updatePausedMcForEnabling(tmPlatBizTmp);
            if (Database.DBS_SUCCESS != returnCode) {
                rglog.error("暂停进行中银行对商户手续费优惠营销活动信息更新临时表数据失败！RETURN_CODE=<{}>", returnCode);
                dbsUtil.dbsEndTransaction(false);
                throw new BizException(RespCodeEnum.SYSTEM_ERROR.getRespCode(), RespCodeEnum.SYSTEM_ERROR.getRespDesc());
            }

        } else {
            rglog.error("营销活动状态异常，不可暂停进行中的银行对商户手续费优惠营销活动！MC_STATUS=<{}>", tmMcMchntFeeDiscountInfo.getMcStatus());
            dbsUtil.dbsEndTransaction(false);
            throw new BizException(RespCodeEnum.SYSTEM_ERROR.getRespCode(), RespCodeEnum.SYSTEM_ERROR.getRespDesc());
        }

        dbsUtil.dbsEndTransaction(true);
    }

    /**
     * 获取营销活动商户信息列表(正式表)
     *
     * @param exitFlag     退出标志
     * @param newMchntFlag 新商户标志
     * @return java.util.List<cc.rengu.igas.momp.common.entity.TMMcMchntInfo> 营销活动商户信息表
     * @throws Exception 异常信息
     * @author liujinan
     * @date 2020/8/10 18:35
     */
    private List<TMMcMchntInfo> getAllMcMchntListInfoByinstIdMcMoFlag(String exitFlag, String newMchntFlag) throws Exception {
        List<Object> tmMcMchntInfoList = new ArrayList<>();
        PageInfo pageInfo = new PageInfo();
        int i = 0;
        pageInfo.setPageIndex(i);
        pageInfo.setPageSize(9999);
        TMMcMchntInfo tmMcMchntInfo = new TMMcMchntInfo();
        tmMcMchntInfo.setInstId(globalInstId);
        tmMcMchntInfo.setMcNo(globalMcNo);
        McMchntInfoMapper mcMchntInfoMapper = new McMchntInfoMapperImpl();
        PageResult tmMcMchntInfoPageInfo = mcMchntInfoMapper.selectMcMchntInfoListByinstIdMcMoFlag(globalInstId, globalMcNo, exitFlag, newMchntFlag, pageInfo);
        if (null != tmMcMchntInfoPageInfo && null != tmMcMchntInfoPageInfo.getResult()) {
            tmMcMchntInfoList.addAll(tmMcMchntInfoPageInfo.getResult());
        }
        while (null != tmMcMchntInfoPageInfo && null != tmMcMchntInfoPageInfo.getResult() && tmMcMchntInfoPageInfo.getResult().size() >= 1) {
            i++;
            pageInfo.setPageIndex(i);
            tmMcMchntInfoPageInfo = mcMchntInfoMapper.selectMcMchntInfoListByinstIdMcMoFlag(globalInstId, globalMcNo, exitFlag, newMchntFlag, pageInfo);
            if (null != tmMcMchntInfoPageInfo && null != tmMcMchntInfoPageInfo.getResult()) {
                tmMcMchntInfoList.addAll(tmMcMchntInfoPageInfo.getResult());
            }
        }
        List<TMMcMchntInfo> mcMchntInfoList = tmMcMchntInfoList.stream().map(item -> (TMMcMchntInfo) (item)).collect(Collectors.toList());
        return mcMchntInfoList;
    }

    /**
     * 获取营销活动商户信息列表(正式表)
     *
     * @return java.util.List<cc.rengu.igas.momp.common.entity.TMMcMchntInfo> 营销活动商户信息表
     * @throws Exception 异常信息
     * @author Jinan Liu
     * @date 2020/5/28 18:35
     */
    private List<TMMcMchntInfo> getAllMcMchntListInfo() throws Exception {
        List<Object> tmMcMchntInfoList = new ArrayList<>();
        PageInfo pageInfo = new PageInfo();
        int i = 0;
        pageInfo.setPageIndex(i);
        pageInfo.setPageSize(9999);
        TMMcMchntInfo tmMcMchntInfo = new TMMcMchntInfo();
        tmMcMchntInfo.setInstId(globalInstId);
        tmMcMchntInfo.setMcNo(globalMcNo);
        McMchntInfoMapper mcMchntInfoMapper = new McMchntInfoMapperImpl();
        PageResult tmMcMchntInfoPageInfo = mcMchntInfoMapper.selectMcMchntInfoList(tmMcMchntInfo, pageInfo);
        if (null != tmMcMchntInfoPageInfo && null != tmMcMchntInfoPageInfo.getResult()) {
            tmMcMchntInfoList.addAll(tmMcMchntInfoPageInfo.getResult());
        }
        while (null != tmMcMchntInfoPageInfo && null != tmMcMchntInfoPageInfo.getResult() && tmMcMchntInfoPageInfo.getResult().size() >= 1) {
            i++;
            pageInfo.setPageIndex(i);
            tmMcMchntInfoPageInfo = mcMchntInfoMapper.selectMcMchntInfoList(tmMcMchntInfo, pageInfo);
            if (null != tmMcMchntInfoPageInfo && null != tmMcMchntInfoPageInfo.getResult()) {
                tmMcMchntInfoList.addAll(tmMcMchntInfoPageInfo.getResult());
            }
        }
        List<TMMcMchntInfo> mcMchntInfoList = tmMcMchntInfoList.stream().map(item -> (TMMcMchntInfo) (item)).collect(Collectors.toList());
        return mcMchntInfoList;
    }


}
